Upload
lemien
View
213
Download
0
Embed Size (px)
Citation preview
Advanced Software Engineering 620-520
Wrap-up session
Software Engineering (SE)
bull ldquoSoftware engineering is the application of a systematic disciplined quantifiable approach to the development and maintenance of software and the study of these approaches that is the application of engineering to softwarerdquo
bull ldquo Engineering is the science discipline art and profession of acquiring and applying technical scientific and mathematical knowledge to design and implement materials structures machines devices systems and processes that safely realize a desired objective or inventions rdquo
Source Guide to the Software Engineering Body of Knowledge - 2004 Version IEEE Computer Society
p 1-1 ISBN 0-7695-2330-7 httpwwwswebokorg
SErsquos Achilles heel
bull Cost
bull Time
bull Quality
Why Software projects fail
5 main reasons
bull Unrealistic commitments
bull Bad project management
bull Lack of means to control the projectrsquos progression (process)
bull Use of inappropriate technology (methods tools languages)
ndash Also called the Accidental Complexity
bull Not enough validation and verification
SE challenges
bull Systems bigger and bigger distributed
ndash How to validate components (modules) developed separately
bull Inter-components validation integration
ndash Problems due to managing resources (human and means)
bull Hire the right skills use the good tools languages etc
bull Project management
ndash Use the right process planning offshorehellip
SE challenges
bull Components(modules) are more and more complex
ndash The problem of intra-component validation
ndash It is still too much expensive to proof (verify) the code
bull Only few people have expertise to do this
bull In practice
ndash Dedicated to very critical components
SE challenges
bull Requirements that constantly changeevolve
ndash Nokia reported that
bull 50 of requirements changed after the beginning of the project
bull 60 of these changed at least 2 more times
bull This is the usual situation not an exceptional one
bull When walking on water or developing software from a specification
can be an easier task
ndash if both are frozen (Edward V Berard)
Modeling with UML
What is Modeling
Building an abstract representation of reality
Abstraction =
bull Ignoring the insgnificant details (depending on the aspectsviewpoint we are interested in)
bull Bringing out the most important details
ndash Important= What it is imporant or not depends on the purpose of the model (is it just for communication Code generation Verification) and which aspect of the system you want to capture
Modeling an other definition
Modeling in the broadest sense is the cost-effective use of something in place of
something else for some cognitive purpose It allows us to use something that
is simpler safer or cheaper than reality instead of reality for some purpose
A Model represents reality for the given purpose the model is an abstraction of
reality in the sense that it cannot represent all aspects of reality This allows us
to deal with the world in a simplified manner avoiding the complexity danger
and irreversibility of reality
Par Jeff Rothenberg laquo The nature of modeling raquo
bull Attention abstraction = simplification
ndash Modeling may ease understanding the problem communicating around its
different aspects but it never simplifies the problem itself
Model Example
bull The pipe example according to Magritte
ndash ldquoThis is not a Piperdquo
reperesents
The system The Model
Abstraction Vs Viewpoint
Example Google Maps
bull Different levels of abstractions
bull Different viewpoints
Why Modeling
To communicate
To manage complexity
To sustain the companyrsquos know-how and assets
For a better productivity
Software = Code
bull Do you really still think that
bull Not the case anymore
ndash Software= Documentation + Models+ Code
ndash Several models views for the same Software
ndash Documentation can be partially generated from Models
ndash Code can be partially generated from Models (100 in some cases)
bull With Models today we can have
ndash A better productivity better communication and a better specification of the
problemsystem under study
Different development phases covered by UML
bull Requirement
bull Analysis
bull Design
bull Implementation
bull Testing
bull Deployment
bull Maintenance
Well covered by UML
Arguable
implementation if UML is used with option (3) If
you have good code generators
Testing some test cases can be generated from
sequence diagramshellipbut not sufficient
Deployment UML provides a diagram for that but
no automation for this step
Maintenance through round trip engineering
reverse engineering the application of design
patterns
UML diagrams and viewpoints
Package Diagram
GRH Paye
Fondation
Gestion Activiteacute
InstanceCandidat
BibliothegravequeTerminal
searchItemByTitle
findItemByTitle
Sequence Diagram Activity diagram
ActeurEmployeacute ActeurManager ActeurRH
Creacuteer demande de poste
Creacuteer une offre demploi
Examiner demande de poste
Rechercher des candidats
Telecom
Organisme
PersonnePhysiqueNationalite PersonneMorale
est formeacute de
11
LienTypeLien
Personne
Adresse
1
1
possegravede
possegravede
1 Auteur
Groupe
1
Class Diagram
Videacuteothegraveque
Louer un DVD
Rendre un DVD
Use Case Diagram
State Machines Diagram
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Software Engineering (SE)
bull ldquoSoftware engineering is the application of a systematic disciplined quantifiable approach to the development and maintenance of software and the study of these approaches that is the application of engineering to softwarerdquo
bull ldquo Engineering is the science discipline art and profession of acquiring and applying technical scientific and mathematical knowledge to design and implement materials structures machines devices systems and processes that safely realize a desired objective or inventions rdquo
Source Guide to the Software Engineering Body of Knowledge - 2004 Version IEEE Computer Society
p 1-1 ISBN 0-7695-2330-7 httpwwwswebokorg
SErsquos Achilles heel
bull Cost
bull Time
bull Quality
Why Software projects fail
5 main reasons
bull Unrealistic commitments
bull Bad project management
bull Lack of means to control the projectrsquos progression (process)
bull Use of inappropriate technology (methods tools languages)
ndash Also called the Accidental Complexity
bull Not enough validation and verification
SE challenges
bull Systems bigger and bigger distributed
ndash How to validate components (modules) developed separately
bull Inter-components validation integration
ndash Problems due to managing resources (human and means)
bull Hire the right skills use the good tools languages etc
bull Project management
ndash Use the right process planning offshorehellip
SE challenges
bull Components(modules) are more and more complex
ndash The problem of intra-component validation
ndash It is still too much expensive to proof (verify) the code
bull Only few people have expertise to do this
bull In practice
ndash Dedicated to very critical components
SE challenges
bull Requirements that constantly changeevolve
ndash Nokia reported that
bull 50 of requirements changed after the beginning of the project
bull 60 of these changed at least 2 more times
bull This is the usual situation not an exceptional one
bull When walking on water or developing software from a specification
can be an easier task
ndash if both are frozen (Edward V Berard)
Modeling with UML
What is Modeling
Building an abstract representation of reality
Abstraction =
bull Ignoring the insgnificant details (depending on the aspectsviewpoint we are interested in)
bull Bringing out the most important details
ndash Important= What it is imporant or not depends on the purpose of the model (is it just for communication Code generation Verification) and which aspect of the system you want to capture
Modeling an other definition
Modeling in the broadest sense is the cost-effective use of something in place of
something else for some cognitive purpose It allows us to use something that
is simpler safer or cheaper than reality instead of reality for some purpose
A Model represents reality for the given purpose the model is an abstraction of
reality in the sense that it cannot represent all aspects of reality This allows us
to deal with the world in a simplified manner avoiding the complexity danger
and irreversibility of reality
Par Jeff Rothenberg laquo The nature of modeling raquo
bull Attention abstraction = simplification
ndash Modeling may ease understanding the problem communicating around its
different aspects but it never simplifies the problem itself
Model Example
bull The pipe example according to Magritte
ndash ldquoThis is not a Piperdquo
reperesents
The system The Model
Abstraction Vs Viewpoint
Example Google Maps
bull Different levels of abstractions
bull Different viewpoints
Why Modeling
To communicate
To manage complexity
To sustain the companyrsquos know-how and assets
For a better productivity
Software = Code
bull Do you really still think that
bull Not the case anymore
ndash Software= Documentation + Models+ Code
ndash Several models views for the same Software
ndash Documentation can be partially generated from Models
ndash Code can be partially generated from Models (100 in some cases)
bull With Models today we can have
ndash A better productivity better communication and a better specification of the
problemsystem under study
Different development phases covered by UML
bull Requirement
bull Analysis
bull Design
bull Implementation
bull Testing
bull Deployment
bull Maintenance
Well covered by UML
Arguable
implementation if UML is used with option (3) If
you have good code generators
Testing some test cases can be generated from
sequence diagramshellipbut not sufficient
Deployment UML provides a diagram for that but
no automation for this step
Maintenance through round trip engineering
reverse engineering the application of design
patterns
UML diagrams and viewpoints
Package Diagram
GRH Paye
Fondation
Gestion Activiteacute
InstanceCandidat
BibliothegravequeTerminal
searchItemByTitle
findItemByTitle
Sequence Diagram Activity diagram
ActeurEmployeacute ActeurManager ActeurRH
Creacuteer demande de poste
Creacuteer une offre demploi
Examiner demande de poste
Rechercher des candidats
Telecom
Organisme
PersonnePhysiqueNationalite PersonneMorale
est formeacute de
11
LienTypeLien
Personne
Adresse
1
1
possegravede
possegravede
1 Auteur
Groupe
1
Class Diagram
Videacuteothegraveque
Louer un DVD
Rendre un DVD
Use Case Diagram
State Machines Diagram
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
SErsquos Achilles heel
bull Cost
bull Time
bull Quality
Why Software projects fail
5 main reasons
bull Unrealistic commitments
bull Bad project management
bull Lack of means to control the projectrsquos progression (process)
bull Use of inappropriate technology (methods tools languages)
ndash Also called the Accidental Complexity
bull Not enough validation and verification
SE challenges
bull Systems bigger and bigger distributed
ndash How to validate components (modules) developed separately
bull Inter-components validation integration
ndash Problems due to managing resources (human and means)
bull Hire the right skills use the good tools languages etc
bull Project management
ndash Use the right process planning offshorehellip
SE challenges
bull Components(modules) are more and more complex
ndash The problem of intra-component validation
ndash It is still too much expensive to proof (verify) the code
bull Only few people have expertise to do this
bull In practice
ndash Dedicated to very critical components
SE challenges
bull Requirements that constantly changeevolve
ndash Nokia reported that
bull 50 of requirements changed after the beginning of the project
bull 60 of these changed at least 2 more times
bull This is the usual situation not an exceptional one
bull When walking on water or developing software from a specification
can be an easier task
ndash if both are frozen (Edward V Berard)
Modeling with UML
What is Modeling
Building an abstract representation of reality
Abstraction =
bull Ignoring the insgnificant details (depending on the aspectsviewpoint we are interested in)
bull Bringing out the most important details
ndash Important= What it is imporant or not depends on the purpose of the model (is it just for communication Code generation Verification) and which aspect of the system you want to capture
Modeling an other definition
Modeling in the broadest sense is the cost-effective use of something in place of
something else for some cognitive purpose It allows us to use something that
is simpler safer or cheaper than reality instead of reality for some purpose
A Model represents reality for the given purpose the model is an abstraction of
reality in the sense that it cannot represent all aspects of reality This allows us
to deal with the world in a simplified manner avoiding the complexity danger
and irreversibility of reality
Par Jeff Rothenberg laquo The nature of modeling raquo
bull Attention abstraction = simplification
ndash Modeling may ease understanding the problem communicating around its
different aspects but it never simplifies the problem itself
Model Example
bull The pipe example according to Magritte
ndash ldquoThis is not a Piperdquo
reperesents
The system The Model
Abstraction Vs Viewpoint
Example Google Maps
bull Different levels of abstractions
bull Different viewpoints
Why Modeling
To communicate
To manage complexity
To sustain the companyrsquos know-how and assets
For a better productivity
Software = Code
bull Do you really still think that
bull Not the case anymore
ndash Software= Documentation + Models+ Code
ndash Several models views for the same Software
ndash Documentation can be partially generated from Models
ndash Code can be partially generated from Models (100 in some cases)
bull With Models today we can have
ndash A better productivity better communication and a better specification of the
problemsystem under study
Different development phases covered by UML
bull Requirement
bull Analysis
bull Design
bull Implementation
bull Testing
bull Deployment
bull Maintenance
Well covered by UML
Arguable
implementation if UML is used with option (3) If
you have good code generators
Testing some test cases can be generated from
sequence diagramshellipbut not sufficient
Deployment UML provides a diagram for that but
no automation for this step
Maintenance through round trip engineering
reverse engineering the application of design
patterns
UML diagrams and viewpoints
Package Diagram
GRH Paye
Fondation
Gestion Activiteacute
InstanceCandidat
BibliothegravequeTerminal
searchItemByTitle
findItemByTitle
Sequence Diagram Activity diagram
ActeurEmployeacute ActeurManager ActeurRH
Creacuteer demande de poste
Creacuteer une offre demploi
Examiner demande de poste
Rechercher des candidats
Telecom
Organisme
PersonnePhysiqueNationalite PersonneMorale
est formeacute de
11
LienTypeLien
Personne
Adresse
1
1
possegravede
possegravede
1 Auteur
Groupe
1
Class Diagram
Videacuteothegraveque
Louer un DVD
Rendre un DVD
Use Case Diagram
State Machines Diagram
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Why Software projects fail
5 main reasons
bull Unrealistic commitments
bull Bad project management
bull Lack of means to control the projectrsquos progression (process)
bull Use of inappropriate technology (methods tools languages)
ndash Also called the Accidental Complexity
bull Not enough validation and verification
SE challenges
bull Systems bigger and bigger distributed
ndash How to validate components (modules) developed separately
bull Inter-components validation integration
ndash Problems due to managing resources (human and means)
bull Hire the right skills use the good tools languages etc
bull Project management
ndash Use the right process planning offshorehellip
SE challenges
bull Components(modules) are more and more complex
ndash The problem of intra-component validation
ndash It is still too much expensive to proof (verify) the code
bull Only few people have expertise to do this
bull In practice
ndash Dedicated to very critical components
SE challenges
bull Requirements that constantly changeevolve
ndash Nokia reported that
bull 50 of requirements changed after the beginning of the project
bull 60 of these changed at least 2 more times
bull This is the usual situation not an exceptional one
bull When walking on water or developing software from a specification
can be an easier task
ndash if both are frozen (Edward V Berard)
Modeling with UML
What is Modeling
Building an abstract representation of reality
Abstraction =
bull Ignoring the insgnificant details (depending on the aspectsviewpoint we are interested in)
bull Bringing out the most important details
ndash Important= What it is imporant or not depends on the purpose of the model (is it just for communication Code generation Verification) and which aspect of the system you want to capture
Modeling an other definition
Modeling in the broadest sense is the cost-effective use of something in place of
something else for some cognitive purpose It allows us to use something that
is simpler safer or cheaper than reality instead of reality for some purpose
A Model represents reality for the given purpose the model is an abstraction of
reality in the sense that it cannot represent all aspects of reality This allows us
to deal with the world in a simplified manner avoiding the complexity danger
and irreversibility of reality
Par Jeff Rothenberg laquo The nature of modeling raquo
bull Attention abstraction = simplification
ndash Modeling may ease understanding the problem communicating around its
different aspects but it never simplifies the problem itself
Model Example
bull The pipe example according to Magritte
ndash ldquoThis is not a Piperdquo
reperesents
The system The Model
Abstraction Vs Viewpoint
Example Google Maps
bull Different levels of abstractions
bull Different viewpoints
Why Modeling
To communicate
To manage complexity
To sustain the companyrsquos know-how and assets
For a better productivity
Software = Code
bull Do you really still think that
bull Not the case anymore
ndash Software= Documentation + Models+ Code
ndash Several models views for the same Software
ndash Documentation can be partially generated from Models
ndash Code can be partially generated from Models (100 in some cases)
bull With Models today we can have
ndash A better productivity better communication and a better specification of the
problemsystem under study
Different development phases covered by UML
bull Requirement
bull Analysis
bull Design
bull Implementation
bull Testing
bull Deployment
bull Maintenance
Well covered by UML
Arguable
implementation if UML is used with option (3) If
you have good code generators
Testing some test cases can be generated from
sequence diagramshellipbut not sufficient
Deployment UML provides a diagram for that but
no automation for this step
Maintenance through round trip engineering
reverse engineering the application of design
patterns
UML diagrams and viewpoints
Package Diagram
GRH Paye
Fondation
Gestion Activiteacute
InstanceCandidat
BibliothegravequeTerminal
searchItemByTitle
findItemByTitle
Sequence Diagram Activity diagram
ActeurEmployeacute ActeurManager ActeurRH
Creacuteer demande de poste
Creacuteer une offre demploi
Examiner demande de poste
Rechercher des candidats
Telecom
Organisme
PersonnePhysiqueNationalite PersonneMorale
est formeacute de
11
LienTypeLien
Personne
Adresse
1
1
possegravede
possegravede
1 Auteur
Groupe
1
Class Diagram
Videacuteothegraveque
Louer un DVD
Rendre un DVD
Use Case Diagram
State Machines Diagram
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
SE challenges
bull Systems bigger and bigger distributed
ndash How to validate components (modules) developed separately
bull Inter-components validation integration
ndash Problems due to managing resources (human and means)
bull Hire the right skills use the good tools languages etc
bull Project management
ndash Use the right process planning offshorehellip
SE challenges
bull Components(modules) are more and more complex
ndash The problem of intra-component validation
ndash It is still too much expensive to proof (verify) the code
bull Only few people have expertise to do this
bull In practice
ndash Dedicated to very critical components
SE challenges
bull Requirements that constantly changeevolve
ndash Nokia reported that
bull 50 of requirements changed after the beginning of the project
bull 60 of these changed at least 2 more times
bull This is the usual situation not an exceptional one
bull When walking on water or developing software from a specification
can be an easier task
ndash if both are frozen (Edward V Berard)
Modeling with UML
What is Modeling
Building an abstract representation of reality
Abstraction =
bull Ignoring the insgnificant details (depending on the aspectsviewpoint we are interested in)
bull Bringing out the most important details
ndash Important= What it is imporant or not depends on the purpose of the model (is it just for communication Code generation Verification) and which aspect of the system you want to capture
Modeling an other definition
Modeling in the broadest sense is the cost-effective use of something in place of
something else for some cognitive purpose It allows us to use something that
is simpler safer or cheaper than reality instead of reality for some purpose
A Model represents reality for the given purpose the model is an abstraction of
reality in the sense that it cannot represent all aspects of reality This allows us
to deal with the world in a simplified manner avoiding the complexity danger
and irreversibility of reality
Par Jeff Rothenberg laquo The nature of modeling raquo
bull Attention abstraction = simplification
ndash Modeling may ease understanding the problem communicating around its
different aspects but it never simplifies the problem itself
Model Example
bull The pipe example according to Magritte
ndash ldquoThis is not a Piperdquo
reperesents
The system The Model
Abstraction Vs Viewpoint
Example Google Maps
bull Different levels of abstractions
bull Different viewpoints
Why Modeling
To communicate
To manage complexity
To sustain the companyrsquos know-how and assets
For a better productivity
Software = Code
bull Do you really still think that
bull Not the case anymore
ndash Software= Documentation + Models+ Code
ndash Several models views for the same Software
ndash Documentation can be partially generated from Models
ndash Code can be partially generated from Models (100 in some cases)
bull With Models today we can have
ndash A better productivity better communication and a better specification of the
problemsystem under study
Different development phases covered by UML
bull Requirement
bull Analysis
bull Design
bull Implementation
bull Testing
bull Deployment
bull Maintenance
Well covered by UML
Arguable
implementation if UML is used with option (3) If
you have good code generators
Testing some test cases can be generated from
sequence diagramshellipbut not sufficient
Deployment UML provides a diagram for that but
no automation for this step
Maintenance through round trip engineering
reverse engineering the application of design
patterns
UML diagrams and viewpoints
Package Diagram
GRH Paye
Fondation
Gestion Activiteacute
InstanceCandidat
BibliothegravequeTerminal
searchItemByTitle
findItemByTitle
Sequence Diagram Activity diagram
ActeurEmployeacute ActeurManager ActeurRH
Creacuteer demande de poste
Creacuteer une offre demploi
Examiner demande de poste
Rechercher des candidats
Telecom
Organisme
PersonnePhysiqueNationalite PersonneMorale
est formeacute de
11
LienTypeLien
Personne
Adresse
1
1
possegravede
possegravede
1 Auteur
Groupe
1
Class Diagram
Videacuteothegraveque
Louer un DVD
Rendre un DVD
Use Case Diagram
State Machines Diagram
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
SE challenges
bull Components(modules) are more and more complex
ndash The problem of intra-component validation
ndash It is still too much expensive to proof (verify) the code
bull Only few people have expertise to do this
bull In practice
ndash Dedicated to very critical components
SE challenges
bull Requirements that constantly changeevolve
ndash Nokia reported that
bull 50 of requirements changed after the beginning of the project
bull 60 of these changed at least 2 more times
bull This is the usual situation not an exceptional one
bull When walking on water or developing software from a specification
can be an easier task
ndash if both are frozen (Edward V Berard)
Modeling with UML
What is Modeling
Building an abstract representation of reality
Abstraction =
bull Ignoring the insgnificant details (depending on the aspectsviewpoint we are interested in)
bull Bringing out the most important details
ndash Important= What it is imporant or not depends on the purpose of the model (is it just for communication Code generation Verification) and which aspect of the system you want to capture
Modeling an other definition
Modeling in the broadest sense is the cost-effective use of something in place of
something else for some cognitive purpose It allows us to use something that
is simpler safer or cheaper than reality instead of reality for some purpose
A Model represents reality for the given purpose the model is an abstraction of
reality in the sense that it cannot represent all aspects of reality This allows us
to deal with the world in a simplified manner avoiding the complexity danger
and irreversibility of reality
Par Jeff Rothenberg laquo The nature of modeling raquo
bull Attention abstraction = simplification
ndash Modeling may ease understanding the problem communicating around its
different aspects but it never simplifies the problem itself
Model Example
bull The pipe example according to Magritte
ndash ldquoThis is not a Piperdquo
reperesents
The system The Model
Abstraction Vs Viewpoint
Example Google Maps
bull Different levels of abstractions
bull Different viewpoints
Why Modeling
To communicate
To manage complexity
To sustain the companyrsquos know-how and assets
For a better productivity
Software = Code
bull Do you really still think that
bull Not the case anymore
ndash Software= Documentation + Models+ Code
ndash Several models views for the same Software
ndash Documentation can be partially generated from Models
ndash Code can be partially generated from Models (100 in some cases)
bull With Models today we can have
ndash A better productivity better communication and a better specification of the
problemsystem under study
Different development phases covered by UML
bull Requirement
bull Analysis
bull Design
bull Implementation
bull Testing
bull Deployment
bull Maintenance
Well covered by UML
Arguable
implementation if UML is used with option (3) If
you have good code generators
Testing some test cases can be generated from
sequence diagramshellipbut not sufficient
Deployment UML provides a diagram for that but
no automation for this step
Maintenance through round trip engineering
reverse engineering the application of design
patterns
UML diagrams and viewpoints
Package Diagram
GRH Paye
Fondation
Gestion Activiteacute
InstanceCandidat
BibliothegravequeTerminal
searchItemByTitle
findItemByTitle
Sequence Diagram Activity diagram
ActeurEmployeacute ActeurManager ActeurRH
Creacuteer demande de poste
Creacuteer une offre demploi
Examiner demande de poste
Rechercher des candidats
Telecom
Organisme
PersonnePhysiqueNationalite PersonneMorale
est formeacute de
11
LienTypeLien
Personne
Adresse
1
1
possegravede
possegravede
1 Auteur
Groupe
1
Class Diagram
Videacuteothegraveque
Louer un DVD
Rendre un DVD
Use Case Diagram
State Machines Diagram
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
SE challenges
bull Requirements that constantly changeevolve
ndash Nokia reported that
bull 50 of requirements changed after the beginning of the project
bull 60 of these changed at least 2 more times
bull This is the usual situation not an exceptional one
bull When walking on water or developing software from a specification
can be an easier task
ndash if both are frozen (Edward V Berard)
Modeling with UML
What is Modeling
Building an abstract representation of reality
Abstraction =
bull Ignoring the insgnificant details (depending on the aspectsviewpoint we are interested in)
bull Bringing out the most important details
ndash Important= What it is imporant or not depends on the purpose of the model (is it just for communication Code generation Verification) and which aspect of the system you want to capture
Modeling an other definition
Modeling in the broadest sense is the cost-effective use of something in place of
something else for some cognitive purpose It allows us to use something that
is simpler safer or cheaper than reality instead of reality for some purpose
A Model represents reality for the given purpose the model is an abstraction of
reality in the sense that it cannot represent all aspects of reality This allows us
to deal with the world in a simplified manner avoiding the complexity danger
and irreversibility of reality
Par Jeff Rothenberg laquo The nature of modeling raquo
bull Attention abstraction = simplification
ndash Modeling may ease understanding the problem communicating around its
different aspects but it never simplifies the problem itself
Model Example
bull The pipe example according to Magritte
ndash ldquoThis is not a Piperdquo
reperesents
The system The Model
Abstraction Vs Viewpoint
Example Google Maps
bull Different levels of abstractions
bull Different viewpoints
Why Modeling
To communicate
To manage complexity
To sustain the companyrsquos know-how and assets
For a better productivity
Software = Code
bull Do you really still think that
bull Not the case anymore
ndash Software= Documentation + Models+ Code
ndash Several models views for the same Software
ndash Documentation can be partially generated from Models
ndash Code can be partially generated from Models (100 in some cases)
bull With Models today we can have
ndash A better productivity better communication and a better specification of the
problemsystem under study
Different development phases covered by UML
bull Requirement
bull Analysis
bull Design
bull Implementation
bull Testing
bull Deployment
bull Maintenance
Well covered by UML
Arguable
implementation if UML is used with option (3) If
you have good code generators
Testing some test cases can be generated from
sequence diagramshellipbut not sufficient
Deployment UML provides a diagram for that but
no automation for this step
Maintenance through round trip engineering
reverse engineering the application of design
patterns
UML diagrams and viewpoints
Package Diagram
GRH Paye
Fondation
Gestion Activiteacute
InstanceCandidat
BibliothegravequeTerminal
searchItemByTitle
findItemByTitle
Sequence Diagram Activity diagram
ActeurEmployeacute ActeurManager ActeurRH
Creacuteer demande de poste
Creacuteer une offre demploi
Examiner demande de poste
Rechercher des candidats
Telecom
Organisme
PersonnePhysiqueNationalite PersonneMorale
est formeacute de
11
LienTypeLien
Personne
Adresse
1
1
possegravede
possegravede
1 Auteur
Groupe
1
Class Diagram
Videacuteothegraveque
Louer un DVD
Rendre un DVD
Use Case Diagram
State Machines Diagram
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Modeling with UML
What is Modeling
Building an abstract representation of reality
Abstraction =
bull Ignoring the insgnificant details (depending on the aspectsviewpoint we are interested in)
bull Bringing out the most important details
ndash Important= What it is imporant or not depends on the purpose of the model (is it just for communication Code generation Verification) and which aspect of the system you want to capture
Modeling an other definition
Modeling in the broadest sense is the cost-effective use of something in place of
something else for some cognitive purpose It allows us to use something that
is simpler safer or cheaper than reality instead of reality for some purpose
A Model represents reality for the given purpose the model is an abstraction of
reality in the sense that it cannot represent all aspects of reality This allows us
to deal with the world in a simplified manner avoiding the complexity danger
and irreversibility of reality
Par Jeff Rothenberg laquo The nature of modeling raquo
bull Attention abstraction = simplification
ndash Modeling may ease understanding the problem communicating around its
different aspects but it never simplifies the problem itself
Model Example
bull The pipe example according to Magritte
ndash ldquoThis is not a Piperdquo
reperesents
The system The Model
Abstraction Vs Viewpoint
Example Google Maps
bull Different levels of abstractions
bull Different viewpoints
Why Modeling
To communicate
To manage complexity
To sustain the companyrsquos know-how and assets
For a better productivity
Software = Code
bull Do you really still think that
bull Not the case anymore
ndash Software= Documentation + Models+ Code
ndash Several models views for the same Software
ndash Documentation can be partially generated from Models
ndash Code can be partially generated from Models (100 in some cases)
bull With Models today we can have
ndash A better productivity better communication and a better specification of the
problemsystem under study
Different development phases covered by UML
bull Requirement
bull Analysis
bull Design
bull Implementation
bull Testing
bull Deployment
bull Maintenance
Well covered by UML
Arguable
implementation if UML is used with option (3) If
you have good code generators
Testing some test cases can be generated from
sequence diagramshellipbut not sufficient
Deployment UML provides a diagram for that but
no automation for this step
Maintenance through round trip engineering
reverse engineering the application of design
patterns
UML diagrams and viewpoints
Package Diagram
GRH Paye
Fondation
Gestion Activiteacute
InstanceCandidat
BibliothegravequeTerminal
searchItemByTitle
findItemByTitle
Sequence Diagram Activity diagram
ActeurEmployeacute ActeurManager ActeurRH
Creacuteer demande de poste
Creacuteer une offre demploi
Examiner demande de poste
Rechercher des candidats
Telecom
Organisme
PersonnePhysiqueNationalite PersonneMorale
est formeacute de
11
LienTypeLien
Personne
Adresse
1
1
possegravede
possegravede
1 Auteur
Groupe
1
Class Diagram
Videacuteothegraveque
Louer un DVD
Rendre un DVD
Use Case Diagram
State Machines Diagram
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
What is Modeling
Building an abstract representation of reality
Abstraction =
bull Ignoring the insgnificant details (depending on the aspectsviewpoint we are interested in)
bull Bringing out the most important details
ndash Important= What it is imporant or not depends on the purpose of the model (is it just for communication Code generation Verification) and which aspect of the system you want to capture
Modeling an other definition
Modeling in the broadest sense is the cost-effective use of something in place of
something else for some cognitive purpose It allows us to use something that
is simpler safer or cheaper than reality instead of reality for some purpose
A Model represents reality for the given purpose the model is an abstraction of
reality in the sense that it cannot represent all aspects of reality This allows us
to deal with the world in a simplified manner avoiding the complexity danger
and irreversibility of reality
Par Jeff Rothenberg laquo The nature of modeling raquo
bull Attention abstraction = simplification
ndash Modeling may ease understanding the problem communicating around its
different aspects but it never simplifies the problem itself
Model Example
bull The pipe example according to Magritte
ndash ldquoThis is not a Piperdquo
reperesents
The system The Model
Abstraction Vs Viewpoint
Example Google Maps
bull Different levels of abstractions
bull Different viewpoints
Why Modeling
To communicate
To manage complexity
To sustain the companyrsquos know-how and assets
For a better productivity
Software = Code
bull Do you really still think that
bull Not the case anymore
ndash Software= Documentation + Models+ Code
ndash Several models views for the same Software
ndash Documentation can be partially generated from Models
ndash Code can be partially generated from Models (100 in some cases)
bull With Models today we can have
ndash A better productivity better communication and a better specification of the
problemsystem under study
Different development phases covered by UML
bull Requirement
bull Analysis
bull Design
bull Implementation
bull Testing
bull Deployment
bull Maintenance
Well covered by UML
Arguable
implementation if UML is used with option (3) If
you have good code generators
Testing some test cases can be generated from
sequence diagramshellipbut not sufficient
Deployment UML provides a diagram for that but
no automation for this step
Maintenance through round trip engineering
reverse engineering the application of design
patterns
UML diagrams and viewpoints
Package Diagram
GRH Paye
Fondation
Gestion Activiteacute
InstanceCandidat
BibliothegravequeTerminal
searchItemByTitle
findItemByTitle
Sequence Diagram Activity diagram
ActeurEmployeacute ActeurManager ActeurRH
Creacuteer demande de poste
Creacuteer une offre demploi
Examiner demande de poste
Rechercher des candidats
Telecom
Organisme
PersonnePhysiqueNationalite PersonneMorale
est formeacute de
11
LienTypeLien
Personne
Adresse
1
1
possegravede
possegravede
1 Auteur
Groupe
1
Class Diagram
Videacuteothegraveque
Louer un DVD
Rendre un DVD
Use Case Diagram
State Machines Diagram
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Modeling an other definition
Modeling in the broadest sense is the cost-effective use of something in place of
something else for some cognitive purpose It allows us to use something that
is simpler safer or cheaper than reality instead of reality for some purpose
A Model represents reality for the given purpose the model is an abstraction of
reality in the sense that it cannot represent all aspects of reality This allows us
to deal with the world in a simplified manner avoiding the complexity danger
and irreversibility of reality
Par Jeff Rothenberg laquo The nature of modeling raquo
bull Attention abstraction = simplification
ndash Modeling may ease understanding the problem communicating around its
different aspects but it never simplifies the problem itself
Model Example
bull The pipe example according to Magritte
ndash ldquoThis is not a Piperdquo
reperesents
The system The Model
Abstraction Vs Viewpoint
Example Google Maps
bull Different levels of abstractions
bull Different viewpoints
Why Modeling
To communicate
To manage complexity
To sustain the companyrsquos know-how and assets
For a better productivity
Software = Code
bull Do you really still think that
bull Not the case anymore
ndash Software= Documentation + Models+ Code
ndash Several models views for the same Software
ndash Documentation can be partially generated from Models
ndash Code can be partially generated from Models (100 in some cases)
bull With Models today we can have
ndash A better productivity better communication and a better specification of the
problemsystem under study
Different development phases covered by UML
bull Requirement
bull Analysis
bull Design
bull Implementation
bull Testing
bull Deployment
bull Maintenance
Well covered by UML
Arguable
implementation if UML is used with option (3) If
you have good code generators
Testing some test cases can be generated from
sequence diagramshellipbut not sufficient
Deployment UML provides a diagram for that but
no automation for this step
Maintenance through round trip engineering
reverse engineering the application of design
patterns
UML diagrams and viewpoints
Package Diagram
GRH Paye
Fondation
Gestion Activiteacute
InstanceCandidat
BibliothegravequeTerminal
searchItemByTitle
findItemByTitle
Sequence Diagram Activity diagram
ActeurEmployeacute ActeurManager ActeurRH
Creacuteer demande de poste
Creacuteer une offre demploi
Examiner demande de poste
Rechercher des candidats
Telecom
Organisme
PersonnePhysiqueNationalite PersonneMorale
est formeacute de
11
LienTypeLien
Personne
Adresse
1
1
possegravede
possegravede
1 Auteur
Groupe
1
Class Diagram
Videacuteothegraveque
Louer un DVD
Rendre un DVD
Use Case Diagram
State Machines Diagram
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Model Example
bull The pipe example according to Magritte
ndash ldquoThis is not a Piperdquo
reperesents
The system The Model
Abstraction Vs Viewpoint
Example Google Maps
bull Different levels of abstractions
bull Different viewpoints
Why Modeling
To communicate
To manage complexity
To sustain the companyrsquos know-how and assets
For a better productivity
Software = Code
bull Do you really still think that
bull Not the case anymore
ndash Software= Documentation + Models+ Code
ndash Several models views for the same Software
ndash Documentation can be partially generated from Models
ndash Code can be partially generated from Models (100 in some cases)
bull With Models today we can have
ndash A better productivity better communication and a better specification of the
problemsystem under study
Different development phases covered by UML
bull Requirement
bull Analysis
bull Design
bull Implementation
bull Testing
bull Deployment
bull Maintenance
Well covered by UML
Arguable
implementation if UML is used with option (3) If
you have good code generators
Testing some test cases can be generated from
sequence diagramshellipbut not sufficient
Deployment UML provides a diagram for that but
no automation for this step
Maintenance through round trip engineering
reverse engineering the application of design
patterns
UML diagrams and viewpoints
Package Diagram
GRH Paye
Fondation
Gestion Activiteacute
InstanceCandidat
BibliothegravequeTerminal
searchItemByTitle
findItemByTitle
Sequence Diagram Activity diagram
ActeurEmployeacute ActeurManager ActeurRH
Creacuteer demande de poste
Creacuteer une offre demploi
Examiner demande de poste
Rechercher des candidats
Telecom
Organisme
PersonnePhysiqueNationalite PersonneMorale
est formeacute de
11
LienTypeLien
Personne
Adresse
1
1
possegravede
possegravede
1 Auteur
Groupe
1
Class Diagram
Videacuteothegraveque
Louer un DVD
Rendre un DVD
Use Case Diagram
State Machines Diagram
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Abstraction Vs Viewpoint
Example Google Maps
bull Different levels of abstractions
bull Different viewpoints
Why Modeling
To communicate
To manage complexity
To sustain the companyrsquos know-how and assets
For a better productivity
Software = Code
bull Do you really still think that
bull Not the case anymore
ndash Software= Documentation + Models+ Code
ndash Several models views for the same Software
ndash Documentation can be partially generated from Models
ndash Code can be partially generated from Models (100 in some cases)
bull With Models today we can have
ndash A better productivity better communication and a better specification of the
problemsystem under study
Different development phases covered by UML
bull Requirement
bull Analysis
bull Design
bull Implementation
bull Testing
bull Deployment
bull Maintenance
Well covered by UML
Arguable
implementation if UML is used with option (3) If
you have good code generators
Testing some test cases can be generated from
sequence diagramshellipbut not sufficient
Deployment UML provides a diagram for that but
no automation for this step
Maintenance through round trip engineering
reverse engineering the application of design
patterns
UML diagrams and viewpoints
Package Diagram
GRH Paye
Fondation
Gestion Activiteacute
InstanceCandidat
BibliothegravequeTerminal
searchItemByTitle
findItemByTitle
Sequence Diagram Activity diagram
ActeurEmployeacute ActeurManager ActeurRH
Creacuteer demande de poste
Creacuteer une offre demploi
Examiner demande de poste
Rechercher des candidats
Telecom
Organisme
PersonnePhysiqueNationalite PersonneMorale
est formeacute de
11
LienTypeLien
Personne
Adresse
1
1
possegravede
possegravede
1 Auteur
Groupe
1
Class Diagram
Videacuteothegraveque
Louer un DVD
Rendre un DVD
Use Case Diagram
State Machines Diagram
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Why Modeling
To communicate
To manage complexity
To sustain the companyrsquos know-how and assets
For a better productivity
Software = Code
bull Do you really still think that
bull Not the case anymore
ndash Software= Documentation + Models+ Code
ndash Several models views for the same Software
ndash Documentation can be partially generated from Models
ndash Code can be partially generated from Models (100 in some cases)
bull With Models today we can have
ndash A better productivity better communication and a better specification of the
problemsystem under study
Different development phases covered by UML
bull Requirement
bull Analysis
bull Design
bull Implementation
bull Testing
bull Deployment
bull Maintenance
Well covered by UML
Arguable
implementation if UML is used with option (3) If
you have good code generators
Testing some test cases can be generated from
sequence diagramshellipbut not sufficient
Deployment UML provides a diagram for that but
no automation for this step
Maintenance through round trip engineering
reverse engineering the application of design
patterns
UML diagrams and viewpoints
Package Diagram
GRH Paye
Fondation
Gestion Activiteacute
InstanceCandidat
BibliothegravequeTerminal
searchItemByTitle
findItemByTitle
Sequence Diagram Activity diagram
ActeurEmployeacute ActeurManager ActeurRH
Creacuteer demande de poste
Creacuteer une offre demploi
Examiner demande de poste
Rechercher des candidats
Telecom
Organisme
PersonnePhysiqueNationalite PersonneMorale
est formeacute de
11
LienTypeLien
Personne
Adresse
1
1
possegravede
possegravede
1 Auteur
Groupe
1
Class Diagram
Videacuteothegraveque
Louer un DVD
Rendre un DVD
Use Case Diagram
State Machines Diagram
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Software = Code
bull Do you really still think that
bull Not the case anymore
ndash Software= Documentation + Models+ Code
ndash Several models views for the same Software
ndash Documentation can be partially generated from Models
ndash Code can be partially generated from Models (100 in some cases)
bull With Models today we can have
ndash A better productivity better communication and a better specification of the
problemsystem under study
Different development phases covered by UML
bull Requirement
bull Analysis
bull Design
bull Implementation
bull Testing
bull Deployment
bull Maintenance
Well covered by UML
Arguable
implementation if UML is used with option (3) If
you have good code generators
Testing some test cases can be generated from
sequence diagramshellipbut not sufficient
Deployment UML provides a diagram for that but
no automation for this step
Maintenance through round trip engineering
reverse engineering the application of design
patterns
UML diagrams and viewpoints
Package Diagram
GRH Paye
Fondation
Gestion Activiteacute
InstanceCandidat
BibliothegravequeTerminal
searchItemByTitle
findItemByTitle
Sequence Diagram Activity diagram
ActeurEmployeacute ActeurManager ActeurRH
Creacuteer demande de poste
Creacuteer une offre demploi
Examiner demande de poste
Rechercher des candidats
Telecom
Organisme
PersonnePhysiqueNationalite PersonneMorale
est formeacute de
11
LienTypeLien
Personne
Adresse
1
1
possegravede
possegravede
1 Auteur
Groupe
1
Class Diagram
Videacuteothegraveque
Louer un DVD
Rendre un DVD
Use Case Diagram
State Machines Diagram
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Different development phases covered by UML
bull Requirement
bull Analysis
bull Design
bull Implementation
bull Testing
bull Deployment
bull Maintenance
Well covered by UML
Arguable
implementation if UML is used with option (3) If
you have good code generators
Testing some test cases can be generated from
sequence diagramshellipbut not sufficient
Deployment UML provides a diagram for that but
no automation for this step
Maintenance through round trip engineering
reverse engineering the application of design
patterns
UML diagrams and viewpoints
Package Diagram
GRH Paye
Fondation
Gestion Activiteacute
InstanceCandidat
BibliothegravequeTerminal
searchItemByTitle
findItemByTitle
Sequence Diagram Activity diagram
ActeurEmployeacute ActeurManager ActeurRH
Creacuteer demande de poste
Creacuteer une offre demploi
Examiner demande de poste
Rechercher des candidats
Telecom
Organisme
PersonnePhysiqueNationalite PersonneMorale
est formeacute de
11
LienTypeLien
Personne
Adresse
1
1
possegravede
possegravede
1 Auteur
Groupe
1
Class Diagram
Videacuteothegraveque
Louer un DVD
Rendre un DVD
Use Case Diagram
State Machines Diagram
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
UML diagrams and viewpoints
Package Diagram
GRH Paye
Fondation
Gestion Activiteacute
InstanceCandidat
BibliothegravequeTerminal
searchItemByTitle
findItemByTitle
Sequence Diagram Activity diagram
ActeurEmployeacute ActeurManager ActeurRH
Creacuteer demande de poste
Creacuteer une offre demploi
Examiner demande de poste
Rechercher des candidats
Telecom
Organisme
PersonnePhysiqueNationalite PersonneMorale
est formeacute de
11
LienTypeLien
Personne
Adresse
1
1
possegravede
possegravede
1 Auteur
Groupe
1
Class Diagram
Videacuteothegraveque
Louer un DVD
Rendre un DVD
Use Case Diagram
State Machines Diagram
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
UML Viewpoints
Staticarchitectural aspects -Class diagram
-Object and package diagrams
-Component and composite structure
diagrams
Behavioral aspects of the system -Sequencecollaboration diagrams
-State machines diagram
-Activity diagram
-Time diagram
Functional aspects of the system -Use Case diagram
-Scenarios
-Sequence diagram
- Activity diagram
- State machines diagram (if needed)
Deployment aspects -Deployment diagram
-Component diagram In Red will be used in this course
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
UML Functional viewpoint
- Use case diagram
-Scenarios
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Use Case Diagram
Use Case diagram constituents
ndash Actors
ndash Use Cases
ndash The system being modeled
ndash Relations bull Associations Generalization dependencies
Goals
ndash To communicate around the systemrsquos expected services
ndash Identify Systemrsquos functionalities (in a graphical way)
ndash To highlight the systemrsquos boundaries
ndash Can be used to specify some functional tests
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Use Case Relations
Between Use cases 3 kinds of relations
bull Generalization the sub-UC extends the super-UC with more action Source of ambiguity Agrave Please avoid using this relation (not allowed in this course)
bull Inclusion (ltltincludegtgt) the source UC necessarily needs the target use case for its execution
ndash Use it to factorize common actions between
different use cases
ndash To highlight an important sub-functionality
bull Extension (ltltextendgtgt) a base UC can be Optionally extended by another UC for its execution
bull If you want to be precise when the inclusion or the extension happens you can add an Extension Point
Funds Transfer
Funds Transfer
On Line
Withdraw Cash Identification
ltltincludegtgt
Withdraw Cash
Extension Point
check balance
Check Balance
ltltextendgtgt
Condition User wants to check balance first
Point drsquoextension check balance
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Scenarios
bull They represent instances of UC ndash A scenario describes the actors interaction with the system
bull In natural language but usually represented using Sequence Diag
bull Very used and useful for requirements specification (can hardly do without)
bull They can help you identifying other UC
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Scenarios
bull Every UC will be specified using several scenarios
bull First with a Happy Path scenario(the world is perfect ))
bull Secondary scenarios (exceptions alternatives)
bull UC + Detailed scenarios for each UC =gt Functional
requirement specification
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
UML Staticarchitecture viewpoint
-Class Diagram
-Object Diagram
- Component Diagram
- Package Diagram
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Class Diagram
bull A class diagram is a graph of elements connected by relations
bull Gives the static aspects of your system (structure architecture
main entities relations etc) Company
Company
Person
Employeemembers
01
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Association Notation
Client Account 1
account
Navigability
roles
The name of the association
Multiplicity
01
client
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Association Navigability
Student Course
attends
students attendedCourses
A student follows a set of course From
the student isrsquoit possible to identify the
courses followed A course is followed by a set of
students (0 or many)
public class Student
public Course attendedCourses[]
public Student()
public class Course
public Course()
bull The impact of the navigability multiplicity and rolersquos names on the
generated code
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Associations Aggregation amp Composition
bull Notion of laquo composed of raquo laquo contains raquo laquo is constrcuted fromraquo hellip
bull Reinforces the association semantics (a set of objects that belong to
another object)
Student
School Departmenthas
1 1
member
1
Composition
Aggregation
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Associations Aggregation amp Composition
bull Donrsquot overuse misuse of these association kinds
bull Aggregation is not very used =gt very similar to simple association
ndash Main point cycles are not allowed comparing to associations
bull Avoid specifying your diagrams with questions such as ldquoIf this class has to
be deleted should this one be deleted toordquo This will result in a class
diagram full of compositions
This kind of association must stay exceptional
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Generalization Notation
Shape
Rectangle Circle
bull We say Generalization Specialization
bull Super classe sub-classes
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Interfaces
bull A set of operations without implementation
ndash Just signature
ndash Can be viewed as an abstract class where all the operations are abstract
ndash May contain properties
bull A very powerful Typing mechanism
bull A Class can realize one or multiple interfaces
ndash Has to give an implementation for each of its operations
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Interfaces Notation
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer laquointerfaceraquo
Comparable
isEqual (Object) boolean
isGreater (Object) boolean
Comparable
String
isEqual (Object) boolean
isGreater (Object) boolean
hash () integer
Or
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Packages Example
bull Import elements are imported to the package with a public visibility and it is transitive
bull Access elements are imported to the package with a private visibility Transitivity is not allowed
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Object Diagram Example
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Components diagram Notation
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
copy Reda Bendraou Software Engineering ndash Course 2 Modeling with UML
Deployment diagram
bull Shows how applicationrsquos components are physically deployed in
the applicationrsquos environment
ndash Physical elements (servers departments etc)
ndash Components
bull Very useful to think about distribution performances hardware
required protocols etc
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
UML Behavioral viewpoint
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Objectives and outcomes
bull The objective of behavior modeling is to studyspecify the
behavior of the objects in a system
bull Reminder An OO system is a system made up of objects that
work together to realize some desirable functionality
ndash We have the desired functionality -gt use cases
ndash We have the object structure -gt classes
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Objectives and outcomes
bull We will study three complimentary behavior models
ndash Sequence diagrams specify how objects work together to realize a
single functionality Inter-Object view
ndash Activity diagrams give a more workflow-oriented representation
of how the work is likely to be done (actors activities and
dataflow) Inter-Object view
ndash State Machines specify the global behavior (participation in all
functionalities) of a single object Intra-Object View
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Sequence Diagram
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Sequence diagrams
bull A sequence diagrams (also called ldquointeraction diagramsrdquo) shows a sequence
of messages exchanged by the objects of a system
bull We generally use a sequence diagram to specify the realization of a single
course of action in a use case
ndash Helps us find the methods of our classes
ndash Helps us validate that the logical data structure is sufficient to realize the
functionality
bull Very used in the industry =gt can be used to specify tests
bull Important a sequence diagram represents an instance of a
possible interaction Itrsquos not an exhaustive representation of
the systemrsquos behavior
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Example
bull 2 dimensions
ndash Horizontal axe =gt objects
ndash Vertical axe =gt time
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Other concepts
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Fragments
bull Used to represent loops conditional branches references to
other sequences diagrams etc
Example of a conditional branche
Example of a loop
Optional fragment
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Collaboration Diagrams
bull Same constituents as Sequence diagrams
bull Focus more on the objects involved in the interaction rather
than on the temporal aspects (messages order)
bull Not really used in projects
bull Can be generated automatically from sequence diagrams (some
tools)
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Example
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
State Machines
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
State Machines
bull Attached to a class (object) ndash More exhaustive than sequence diagrams
ndash Describe how the object reacts to changes in its environment
bull Notions of states amp transitions ndash Inspired from David Harel work
bull Probably the more formal diagram in UML
ndash Very used in critical projects (aerospace automotive nuclear plants etc)
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
State
bull A state is described by a rounded rectangle containing
ndash Name unique within the class
ndash Entry and Exit actions instantaneous processes executed by the object on enteringexiting the state
ndash An activity long-lasting processes executed while the object is in that state
bull Often has the same name as the state in which case it can be omitted
Name
enty action
do activity
exit action
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Initial and final states
bull Every state diagram has exactly one initial state and any number of final states
bull The initial state is the point of creation of the object
ndash The transition leaving it is taken when the object is instantiated
ndash This transition may contain a guard condition and an action but not an event
ndash It may have multiple mutually-exclusive outgoing transitions but no incoming
transitions
bull The final state signifies that the object has terminated its execution and has no further reason to exist
ndash It has no outgoing transitions
[ x ]
[ NOT x ]
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Transition
bull A transition describes how an object moves from one state to
another
bull Syntax
bull The transition is taken when the event is received if the guard
condition is true
bull When it is taken the action is executed by the object
event [ guard condition ] action
dont forget the slash
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Examples of Events
bull A condition becomes true
ndash A guard condition
bull Reception of signal from another object
bull Reception of Call operation event
bull Time condition
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Internal Transitions
bull The object remains in the same state
bull The internal transition is triggered every time the event
specified in the state is triggered
bull This is different from a reflexive transition where the object
goes out from the state then comes back
Etat
Ev1 [t=0] faire quelque chose
Ev1 [tgt0] faire autre chose
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Guards example
Attente
ClimatiserVentiler
when (temperature gt 22) [ete]when (temperature gt 22) [hiver]
idle
Fan AC
[winter] [summer]
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Example of composite state
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Notion of concurrent states
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Activity Diagrams
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Activity Diagrams
bull Used to model Workflow or Business Processes
bull Very expressive to model Use Cases
ndash Instead of sequence diagrams for instance
bull More exhaustive and precise
bull From UML 20 possible to model complex algorithms and operationrsquos bodies
bull Can be attached to
ndash A class
ndash An operation
ndash A use-case (workflow)
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Concepts
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Notion of Call Actions
bull An activity can be called from
another activity (CallBehaviorAction)
bull An activity can call a classical
operation (CallOperationAction)
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Signals
bull Can be used to express a timeout for instance
bull To send or to receive an event
ndash To be caught by an AcceptEventAction
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Swim Lanes
bull Used to define the main roles of the business process (the
WHO )
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Requirements
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Requirements Specification
ldquoThe hardest single part of building a software system is
deciding precisely what to build No other part of the
conceptual work is as difficult as establishing the
detailed technical requirements including all the
interfaces to people to machines and to other software
systems No other part of the work so cripples the
resulting system if done wrong No other part is more
difficult to rectify laterrdquo
bull Fred Brooks No Silver Bullet - Essence and Accident in Software Engineering in Computer
(IEEE) vol 20 no 4 pages 10-19 April 1987
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
This is the anchor
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Requirements Specification Driven By
Stakeholders and their Questions bull Customers
ndash What must it do
bull Developers (eg designers)
ndash What do I have to get it to do
bull Testers
ndash What is it supposed to be doing
ndash How would I know it if I saw it
bull Users
ndash What is it supposed to do
bull Others
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Requirements Specification Parts
bull IntroductionBackground
bull Functional
bull Environmental
bull Performance
bull Accuracy
bull Robustness
bull Security
bull Safety
Help stakeholders organize their thoughts about needs by decomposing requirements specification into categories needs and desires Some examples
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Requirement Specification Challenges bull Is it Complete (to the extent required)
ndash Ultimately impossible to be sure about this
bull Is it Consistent (no internal contradictions)
ndash Many possible interpretations of this
bull Is it unambiguous (possible multiple interpretations)
bull Is it sufficently precise
ndash It is possible to be too precise too
bull Is it Feasible
ndash If it asks the impossible it would be good to know it
bull Is it Even (consistent levels of detail)
bull Is it Understandable (what does that mean)
ndash by all stakeholder groups
bull Is there an implementation bias
bull Is there a good basis for proceeding to design
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
A Requirement Specification
Is Never Perfect in All (Any) Aspects
bull Imperfections are often understandable tolerable unavoidable bull Look at real underlying stakeholder needs for the requirements specification (communication clarity precision modifiability) bull Plan requirements content structure relations to meet these needs bull Requirements specification medium is crucial in helping assure needs are met bull Select requirements specification medium to address needs
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
The IEEE 830-1998 Standard
bull rdquoIEEE Recommended Practice for Software Requirements Specificationsrdquo
bull Approved 25 June 1998 (revision of earlier standard)
bull Descriptions of the content and the qualities of a good software requirements specification (SRS)
bull Goal ldquoThe SRS should be correct unambiguous complete
consistent ranked for importance andor stability verifiable modifiable traceablerdquo
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Recommended document structure
1 Introduction
11 Purpose
12 Scope
13 Definitions acronyms and abbreviations (Glossary)
14 References
15 Overview
2 Overall description
21 Product perspective
22 Product functions
23 User characteristics
24 Constraints
25 Assumptions and dependencies
3 Specific requirements
Appendixes
Index
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Key Lessons
Itrsquos not programming
- Programming describes a solution and not a problem
- Programming is constructive
Itrsquos not design
- We do not only describe the software
- We describe the full system (software and
environment)
- No separation between software and environment
- We do so in an incremental way
- We want to understand the system
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Key Lessons
- Identify amp involve all stakeholders
- Requirements determine not just development but
tests
- Use cases are good for test planning
- Requirements should be abstract
- Requirements should be traceable
- Requirements should be verifiable (otherwise they are
wishful thinking)
Object technology helps
- Modularization
- Classifications
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Architecture
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi level architecture
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Software Architecture amp Design Goals
From B Meyer and P Muller
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Why decompose a system
Management - Partition effort
- Clear assignment of requirements to modules
Modification - Decouple parts so that changes to one donrsquot affect
others
Understanding
- Allow understanding system one chunk at a time
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
What is the Nature of Design
Addresses the question HOW bull Goal Indicate how to develop a solution system that will satisfy
requirements
bull Complements ndash Requirements WHAT
ndash System Test Plan HOW WOULD I KNOW IT IF I SAW IT
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Architecture Vs Specification
Architecture ndash High level system design
ndash Concerned with components and the interactions among components
ndash Not with the algorithms or data structures
Specification (Low Level Design) ndash Emphasis on data structures and algorithms
ndash Focus on implementation issues
raquo Stepwise refinement
raquo Evolvability
raquo Use of abstraction
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Architectural Styles
Sets of constraints that are widely used because they offer
understood capabilities and features
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Some important Concerns about
Architecture
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Modularity
Cohesion Vs Coupling
Cohesion interdependence of elements of one module
Each subsystem has a clear responsibility
Coupling interdependence between different modules
Small interfaces between subsystems
Goal high cohesion and low coupling
Modularity increase cohesion decrease coupling
From B Meyer and
P Muller
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Cohesion Vs Coupling in OO design
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Composability
Build software elements so that they may be freely combined with others
to produce new software
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Design Patterns
Use them when possible
GoF book is a good reference but many other patterns exist in literature
Patterns can be in all phases of developmment
- Requirement patterns
- Architectural patterns
- Design patterns
- etc
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
The five secrets of good architecture
1048707 Simplicity of design
1048707 Consistency of design
1048707 Ease of learning of the APIs
1048707 Support for change
1048707 Support for reuse
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Simplicity always remember
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Testing
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Requirements Spec
Test Plan
Test Results must match required behavior
Design
Characteristics of System to be built must match required characteristics
Hi Level
Low level
Code
Code must implement design
Hi level design must show HOW requirements can be met
consistent views
Test plan exercises this code
Focus on ldquoHow do you knowrdquo
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Requirements
Functional Safety
Performance
Robustness
Accuracy
Testplan
Outputs Timing
Setup
Knockdown
Timing limit must meet performance requirement
Inputs
Test inputoutput behavior must match functional requirements
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Testing
Specification Program
describes
implements
Test
Result Expected
Result
compare
Test fails
different
Test succeeds
equals
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
validation
Veacuterificationproof
testing
does the product meet the spec
Testing Validation
ldquoTesting can only show the presence of errors never their absencerdquo EW Dijkstra 1970 Structured Programming and a few other places
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Testing problem
bull We canrsquot afford to test everything and at anytime
ndash We have to make choices about what to test and with which input
values
bull Proving that a program is bug free is an undecidable
(indeterminate) problem
ndash Need to define some realistic heuristics
bull To test a software is to try to make it fail
ndash Software fails =gt Test successful
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Test hierarchy
Problem statement
Requirements
Design
Code
Unitary
Tests
Software delivery to the C
Maintenance
Advanced Design
V cycle
Integration
Tests
system
Tests
Modules
Integration
System
Delivery tests
(with client) Systemrsquos test plan (functional)
Intergation tests
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Testing basic concepts
Implementation Under Test (IUT)
The software (amp possibly hardware) elements to be tested
Test case
Precise specification of one execution intended to uncover a
possible fault
bull Required state amp environment of IUT before execution
bull Inputs
Test run
One execution of a test case
Test suite
A collection of test cases
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Testing basic concepts
Expected results (for a test case)
Precise specification of what the test is expected to yield in the absence of a
fault
fault
bull Returned values
bull Exceptions
bull Resulting state of program amp environment
bull Non-functional characteristics (time memoryhellip)
bull Messages
Test oracle
A mechanism to determine whether a test run satisfies the expected results
1048707 Output is generally just ldquopassrdquo or ldquofailrdquo
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Testing basic concepts
Test driver
A program or program element (eg class) used to apply test cases to
an IUT
Stub
A temporary implementation of a software element replacing its actual
implementation during testing of other elements relying on it
Generally doesnrsquot satisfy the elementrsquos full specification
May serve as placeholder for
bull A software element that has not yet been written
bull External software that cannot be run for the test (eg
bull because it requires access to hardware or a live database)
bull A software element that takes too much time or memory to
bull run and whose results can be simulated for testing purposes
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Test Classification
By Goal
bull Functional test
bull Performance test
bull Stress (or ldquoloadrdquo) test
Unitary Tests
Integration Tests
System Tests
Structural
Testing
Functional Testing
By scope
Fault-directed testing
Goal reveal faults through failures
1048707 Unit and integration testing
Conformance-directed testing
Goal assess conformance to required capabilities
1048707 System testing
Acceptance testing
Goal enable customer to decide whether to accept a
product
Regression testing
Goal Retest previously tested element after changes to
assess whether they have re-introduced faults or
uncovered new ones
Mutation testing
Goal Introduce faults to assess test case quality
By intent
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Testing Process
bull Identify parts of the software to be tested
bull Identify interesting input values (next slide)
bull Identify expected results (functional) and execution
characteristics (non-functional)
bull Run the software on the input values
bull Compare results amp execution characteristics to expectations
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
How to identify interesting inputs
bull Need for realistic inputs would not be feasible to test all values
bull Partition testing select elements from a partition of the input set ie a set of
subsets that is
bull Complete union of subsets covers entire domain
bull Pairwise disjoint no two subsets intersect
bull Purpose (or hope)
bull For any input value that produces a failure some other in the same
subset produces a similar failure
bull Common abuse of language ldquoa partitionrdquo for ldquoone of the subsets in the
partitionrdquo
bull Better called ldquoequivalence class (ec)rdquo
bull Each ec should at least be used by one test case
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Test Quality notion of Coverage
Goal to assess the effectiveness of a test suite
=gtMeasure how many instructions in your program are reached
(executed) by your test
How it works
bull Choose a kind of program element eg instructions (instruction
coverage) or paths (path coverage)
bull Count how many are executed at least once
bull Report as percentage
100 coverage achieved by a test suite =gt every instruction in the
element tested has been executed at least by one test
Known tools Emma Jcoverage Ncoveretc
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Test Quality Mutation testing
Creation of tests still poses the question whether the tests are
correct and sufficiently cover the requirements that have originated
the implementation bull Quis custodiet ipsos custodes [Who will guard the guards])
bull In our case who tests the tester
Mutation testing
Idea make small changes to the program source code (so that the modified
versions still compile) and see if your test cases fail for the modified versions
Purpose estimate the quality of your test suite
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
What it is Mutation testing
if a mutant is introduced without the behavior (generally output) of the
program being affected this indicates - The code that had been mutated was never executed (dead code)
- The test suite was unable to locate the faults represented by the mutant
Mutants are based on well-defined mutation operators - mimic typical programming errors (ex using the wrong operator or variable
name)
- force the creation of valuable tests (ex dividing each expression by zero)
Disadvantage
- A large number of mutants usually are introduced into a large program
- Requires the compilation and execution of an extremely large number of
copies of the program
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Mutants example
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
What about Standards
IEEE 829
IEEE Standard for Software Test Documentation 1998
Can be found at httptinyurlcom35pcp6 (shortcut for httpwwwruleworkscouktestguidedocuments
IEEE20Standard20for20Software20Test20Documentationpdf)
Specifies a set of test documents and their form
For an overview see the Wikipedia entry
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
IEEE 829 Test plan structure
a) Test plan identifier
b) Introduction
c) Test items
d) Features to be tested
e) Features not to be tested
f) Approach
g) Item passfail criteria
h) Suspension criteria and resumption
requirements
i) Test deliverables
j) Testing tasks
k) Environmental needs
l) Responsibilities
m) Staffing and training needs
n) Schedule
o) Risks and contingencies
p) Approvals
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Hibernate
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Non-Transparent Persistency
bull It is up to the developer to code the data access
bull Object code mixed with SQL Exception proper to DB connectivity (ex SQL exceptions etc)
bull Not natural object oriented programming
bull Needs both expertise in the OO and in writing sound and optimal SQL requests
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Non-Transparent Persistency persistence with JDBC
Connection connexion = null
try
needs the driver to be loaded first using the class for name method + catch exceptions
Connection connexion = DriverManagergetConnection( baseODBC )
connexionsetAutoCommit( false )
Float amount = new Float( 50 )
String request = UPDATE Bank SET balance=(balance -1000) WHERE holder=
PreparedStatement statement = connexionprepareStatement(request )
statementsetString( 1 ldquonamerdquo )
statementexecuteUpdate()
client2check() throws an exception
request = UPDATE Bank SET balance =(balance +1000) WHERE holder =
statement = connexionprepareStatement(request )
statementsetString( 1 ldquordquo )
statementexecuteUpdate()
connexioncommit()
catch( Exception e )
connexionrollback()
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Transparent Persistency ORM tools
bull Natural OO programming Developer does not have to deal with the persistency layer
bull Less code related to data access exceptions (up to 40 less)
bull The SQL generated by the ORM tools has been proven to be more optimal than most developerrsquos hand-written SQL requests
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Object-relational mapping with Hibernate
Obtention drsquoune session Session session = HibernateUtilgetSessionFactory()getCurrentSession()
deacutemarrer une transaction sessionbeginTransaction() persister lrsquoobjet sessionsave(contact) recharger lrsquoobjet agrave partir de la session createdContact=(Contact) sessionload(Contactclass contactgetIdContact()) committer la transaction
sessiongetTransaction()commit()
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Hibernate Core
Session Factory
bull Knows the mappings between classes and tables
bull Provider of Sessions
bull Heavy Object (apply singleton pattern)
Session
bull Bridge between your application and the data base
bull Allows CRUD operations on applicationrsquos objects
bull Masks the JDBC Layer
bull This is the first cache level
bull Light Object
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Objects life cycle within Hibernate
Transient
Persistent
Detached
delete
clear evict close merge lock update saveOrUpdate
persist save saveOrUpdate
garbage collector
garbage collector
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Hibernate configuration
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Hibernate configuration the hibernatecfgxml file
Important One file by project In your root source package
bull To get a SessionFactory
ltxml version=10 encoding=UTF-8gt
ltDOCTYPE hibernate-configuration PUBLIC
-HibernateHibernate Configuration DTD 30EN
httphibernatesourceforgenethibernate-configuration-30dtdgt
lthibernate-configurationgt
ltsession-factorygt
ltndash data base connection details--gt
ltproperty name=hibernateconnectiondriver_classgtcommysqljdbcDriverltpropertygt
ltproperty name=hibernateconnectionurlgtjdbcmysqllocalhostyour_DB_nameltpropertygt
ltproperty name=hibernateconnectionusernamegtyour_user_nameltpropertygt
ltproperty name=hibernateconnectionpasswordgt your_db_password ltpropertygt
ltproperty name=hibernatedialectgtorghibernatedialectMySQLDialectltpropertygt
ltndash here the value update means that the data base schema will not be created each time you run the application but it will be just updated To
create it each time put ldquocreaterdquo instead--gt
ltproperty name=hbm2ddlautogtupdateltpropertygt
ltndash link to mapping files --gt
ltmapping resource=orglip6hibernatetutoContacthbmxmlgt
ltsession-factorygt
lthibernate-configurationgt
SessionFactory sessionFactory = configurationbuildSessionFactory()
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
bull Defines how a class will be mapped (made persistent) in the database
bull File in XML format
bull To put in the same package as the source class Usually named MyClasshbmxml if
the class is called MyClass
bull Introduced in more details further
Hibernate Mapping File
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Associations
bull The more complex part when using Hibernate
bull Type Uni or bidirectional
bull Multiplicities of associations
bull 1-1 1-N N-1 M-N
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Hibernate Tags for associations
bull For collections ltsetgt ltlistgt ltmapgtltbaggt ltarraygt et
ltprimitive-arraygt
bull For multiplicities ltone-to-onegt ltone-to-manygt ltmany-to-
onegtltmany-to-manygt
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
The persistence of associated objects
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
sessionpersist( hobby )
sessionpersist( job )
txcommit()
txclose()
Personne Job Hobby
bull Starting from the class diagram
bull How to persist associated objects
bull First solution explicitly persist all the instances
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
2014-2015
The persistence with Cascade
ltclass name=Persongt
ltid name=id column=personIdgt
ltgenerator class=nativegt
ltidgt
ltmany-to-one name=ldquojob class= Job column= jobId
cascade=ldquopersistgt
ltset name=hobbies fetch=select cascade=persistgt
ltkey column=personIdgt
ltone-to-many class=Hobbygt
ltsetgt
ltclassgt
ltclass name=ldquoHobby lazzy=truegt
ltclassgt
ltclass name=ldquoJob lazzy=truegt
ltclassgt
bull Second solution to use cascade
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Person person = new Person()
Hobby hobby = new Hobby()
Job job = new Job()
personaddHobby( hobby )
personsetJob( job )
Session session = HibernateUtilgetSession()
Transaction tx = sessionbeginTransaction()
sessionpersist( person )
txcommit()
txclose()
bull The following program
bull Allows to propagate the persistence to the instances job and hobby
The persistence with Cascade
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
bull Hibernate supports 3 strategies for inheritance
bull a table per class hierarchy
bull a table per subclass
bull a table per concrete class
Inheritance
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Spring Framework
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Spring
ndash Notion of Lightweight Container
ndash AOP (Aspect Oriented Programming) Support
ndash Integration with other frameworks (Struts Hibernate JSF
etc)
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
bullExample
bullpublic class Foo
bull private IBar bar
bull private IBaz baz
bull public Foo(IBar bar_ IBaz baz_)
bull bar = bar_ baz = baz_
bull
bull
+
-The code is easy to understandrealize
-Testable Flexible Extensible
- Forces the separation between the interface and the implementation -
- We still need to create the dependencies but outside the application
This is where SPRING comes into the play
The IoC Approach
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
The IoC Approach
bull Dependency Injection
bull Principle instantiation of the appropriate components
management of the dependencies and the injections
Foo IBar
IBarImpl1
IBarImpl2
IBarImplN
SPRING ltltcreatesgtgt
ltltinjectsgtgt
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
ltbeansgt
ltbean id=beanFoo1 class=somepackageIBarImpl1gt
ltbean id=beanFoo2 class=somepackageIBarImpl2 scope=prototypegt
ltbeansgt
lt-- in case of using a classrsquos static method--gt
ltbean id=exampleBean class=examplesExampleBean2 factory-method=createInstancegt
lt-- in case of using a factoryrsquos class static method--gt
ltbean id=exampleBean factory-bean=myFactoryBean factory-method=createInstancegt
Bean Definition Example
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Springrsquos Dependency Injection
bull Two Ways
bull Injection using Setters (ie setXXX() )
bull Injection using the classrsquos constructor
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
ltbean id=exampleBean class=examplesExampleBeangt
ltproperty name=beanOnegtltref bean=anotherExampleBeangtltpropertygt
ltproperty name=beanTwogtltref bean=yetAnotherBeangtltpropertygt
ltproperty name=integerPropertygtltvaluegt1ltvaluegtltpropertygt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Dependency Injection the Setters way
public class ExampleBean the JAVA class
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public void setBeanOne(AnotherBean beanOne) thisbeanOne = beanOne
public void setBeanTwo(YetAnotherBean beanTwo) thisbeanTwo = beanTwo
public void setIntegerProperty(int i) thisi = i
a reference to another bean
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
public class ExampleBean
private AnotherBean beanOne
private YetAnotherBean beanTwo
private int i
public ExampleBean(AnotherBean anotherBean
YetAnotherBean yetAnotherBean int i)
thisbeanOne = anotherBean
thisbeanTwo = yetAnotherBean
thisi = i
Dependency Injection the Constructor way bull The Java Class
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Dependency Injection the Constructor way bull Bean Definition
ltbean id=exampleBean class=examplesExampleBeangt
ltconstructor-arggtltref bean=anotherExampleBeangtltconstructor-arggt
ltconstructor-arggtltref bean=yetAnotherBeangtltconstructor-arggt
ltconstructor-arg type=intgtltvaluegt1ltvaluegtltconstructor-arggt
ltbeangt
ltbean id=anotherExampleBean class=examplesAnotherBeangt
ltbean id=yetAnotherBean class=examplesYetAnotherBeangt
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Instantiation of Spring lightweight container
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[]applicationContextxml
applicationContext-part2xml)
IFoo foo = (IFoo)contextgetBean(foo)
Bean Factory amp Application Context
Id of the bean defined in the XML file
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Bean Factory amp Application Context
Instantiation of Spring lightweight container in the context of a
WEB Application
ApplicationContext context =
WebApplicationContextUtilsgetWebApplicationContext(getServletContext())
IFoo foo =(IFoo)contextgetBean(foo)
Id of the bean defined in the XML file
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Example of a Spring project Packaging
Spring Project
Bean Definitions File
Your POJOs
Spring Jars
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
AOP Basic Concepts
bull Joinpoint
ndash An Identifiable point in the execution of a program (Constructor a method invocation etc) In Spring AOP it always represents the execution of a method
bull Pointcut
ndash A programmatic expression that selects the Joinpoints where to apply the aspect
bull Advice
ndash Code to be executed beforeafteraround a Joinpoint expressed by a Pointcut
bull Target
ndash The main class for which the aspects have to be woven The caller does not see the difference between the target class and the proxy class (the proxy class implements the same interfaces as the target class
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Weaving of Aspects the Declarative Way
bull ltbeansgt
bull ltaopconfiggt
ltaopaspect id=emailLoggerBeanldquo ref=emailerLoggergt
ltaopbefore
pointcut=execution( send(String String))
and args(address zipcode)
method=log arg-names=ldquozipcode addressgt
ltaopaspectgt
bull ltaopconfiggt
bull ltbean id=emailerLoggerldquo class=exampleEmailLoggergt
bull ltbeansgt
bull Explanation The log method is invocated before all the calls to methods called ldquosendrdquo and having 4 parameters with the first parameter and the forth one are Strings The first and the forth parameters are forwarded to the log method
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
SOA
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Final Exam
bull Please for your final exam consider all the lectures (slides) and not
only those presented here
bull Consider also the Spring and Hibernate Tutorials
bull The final exam is an individual work=gt I trust you )
bull No deadline extension is allowed
bull Final exam is due=gt Thursday May 7th at noon Accessible Tuesday
5th at noon (by email and on my website)
bull Format a zip file with a read me explaining how I should read you r
diagrams files etc
copy Reda Bendraou Software Engineering Course 1 Introduction 127
Thanks
bull For being so tolerant with my English and with my accent
bull For being so respectful in class and through our
communications (meetings emails)
bull Wish you a great career in computer science
copy Reda Bendraou Software Engineering Course 1 Introduction 127