Module 1
The software development life cycle,
a tour of Agile methodologies, and
scenarios for describing use cases
KIT206 Software Design & Development
KIT506 Software Application Design & Implementation
Outline
The bigger picture: software engineering
The software development life cycle
Refresher: the requirements trace matrix
Agile software development (a brief tour)
Scenarios: making use cases concrete
A foretaste of prototyping in systems design
Reading 1: Software Engineering
Section 1.1 (5 pages) in
Software Engineering: Principles and Practice,
3rd ed, by Hans van Vliet, 2008
Location: accompanying readings PDF
Summary: This optional reading provides some
context for the unit as a whole and the notes
that follow. Software engineering is an multi‐
disciplinary problem‐solving process for creating
non‐trivial software systems.
SDLC
While all human‐created products have a life
cycle (from conception through to realisation
and ultimate disposal) software is unusual in
that it is extremely flexible and, as a
consequence, software products can become
highly complex very quickly.
The processes employed over the lifecycle of
software are intended to manage this
complexity so that a reliable and useful product
is created.
Reading 2: SDLC
Section 1.2 (5 pages) in
Software Engineering: Principles and Practice,
3rd ed, by Hans van Vliet, 2008
Location: accompanying readings PDF
Summary: The software development life cycle
can be thought of in terms of distinct phases
(although the reality is rarely so neat). Indeed,
different projects and different software
development approaches may arrange the
phases differently.
Idealised SDLC
Requirements
Analysis &
Specification
Design
Implementation
Testing
Maintenance
this unit
Revisiting the Requirements
Trace Matrix
If you are already familiar with the requirements trace matrix you may wish to
skip to the next section on Agile software development
Requirements validation
Requirements validation is concerned with
demonstrating that the requirements define the
system that the customer really wants
• One way to validate the requirements is to
produce a requirements trace matrix (RTM)
• The RTM is also useful for tracing the
requirements to completion
Requirements Trace Matrix
• A requirements trace matrix is simply a
spreadsheet (produced in Excel, for instance)
• It has the following columns:
– Entry # (sequentially allocated)
– Para # (identifies the location of the requirement
in the Requirements doc)
– Requirement (verbatim text from Requirements
doc)
– Type (see list)
– Release (which release it is planned to be met by)
– Use Case
Requirement Trace Matrix
Process used to create a RTM:
1. Agree to a starting set of documents
2. Extract the “must” statements. Start from the
beginning of the document, get the entire sentence
that has the word “must” in it, give it a sequential
number starting from one, and take note of the
paragraph that it came from. Put this information in
a spreadsheet type format.
3. Extract the “should” statements in the same manner
as the “must” statements.
4. Similarly for “could”
5. Extract derived requirements. A derived
requirement is a requirement that is deduced from
other system knowledge, but not explicitly stated
statement.
Categorising requirements
Label Meaning & usage notes
HW Hardware Requirement
SW Software Requirement
NTH Nice to have (followed by the actual type)
D(#n) Duplicate of RTM entry #n
SWC Software Constraint (followed by # of entry to
which it applies)
DR Derived Requirement
PR Performance Requirement
Identifying use cases in the RTM
The software system is a set of Use Cases
A Use Case is a statement of functionality required
of the software, expressed in the format:
Actor Action Subject
When a row in the RTM indicates a use case record
it using the template
UC##_Actor_Action_Subject
where ## is the RTM entry number and Actor,
Action and Subject are as above
Use Cases
• An Actor represents a stimulus to the
software system. The stimulus can be internal
or external.
• An Action represents a capability of the
software system.
• A Subject represents the item acted upon by
an Action of the software system.
Actors and Subjects are generally nouns,
whereas Actions are generally verbs
Example: Human Resource Information System
The Human Resource Information System was an
assignment case study used in a previous year
Examples will be derived from it in this and
subsequent modules
The following two examples relate to the sample
Requirements Document and RTM for the HRIS,
which can be found in Module 1 on MyLO
Read these two documents now (~3 pages)
5.1 Staff Lists
The user shall be able to view an interactive list of
staff employed by the School. The list will be
accessed by selecting a tab labelled ‘Staff’.
Ideally this list should be visually compact. …
The Staff List view should be able to filter the
listed staff based on their category. …
The School has a large number of staff and being
able to restrict the list in this fashion will allow the
user to find people quickly.
W
H
A
T
W
H
Y
Actor Action
Subject
H
O
W
V
E
R
IF
Y
A use case from the HRIS
5.1 Staff Lists
…
When the user selects a name in the list the system will
show more details about the staff member (referred to as
the Staff Details view), which should include:
• Name
• Campus
…
It would also be useful for each staff member’s current
availability to be displayed: ‘teaching’ (with details of the
unit code and room) if they are in a timetabled class;
‘consulting’ if it is during their consultation times; ‘free’
otherwise. This would allow front desk staff to direct
enquiries appropriately, given a staff member’s availability.
W
H
A
T
W
H
Y
Actor
Action
Subject H
O
W
V
E
R
IF
Y
Another use case from the HRIS
RTM Example
Entry Para Requirement Type Use Case
:
8 5.1.1 The user shall be able to view an interactive list of staff employed by
the School.
SW UC8_User_views_StaffList
9 5.1.1 The list will be accessed by selecting a tab labelled ‘Staff’. SWC 8
10 5.1.1 Ideally this list should be visually compact. SWC 8
11 5.1.1 When the users selects a name in the list the system will show more
details about the staff member (referred to as the Staff Details view),
which should include: Name; Campus; Phone Number; Room
Location; Email Address; Photo; Consultation hours; Table of units he
or she is involved with in the current semester.
SW UC11_User_selects_StaffDetails
… … … … …
13 5.1.2 It would also be useful for each staff member’s current availability to
be displayed: ‘teaching’ (with details of the unit code and room) if
they are in a timetabled class; ‘consulting’ if it is during their
consultation times; ‘free’ otherwise.
SWC 11
14 5.1.3 The Staff List view should be able to filter the listed staff based on
their category.
SWC 8
15 5.1.3 The user should be able to list all staff, academic, technical,
administrative, and casual.
SWC 8
This excerpt from the RTM is based on the previous two examples
Agile software development
Reading 3: SDLC, introducing Agile
Chapter 3 up to 3.2.1 (exclusive) (6 pages) in
Software Engineering: Principles and Practice, 3rd ed, by
Hans van Vliet, 2008
Location: accompanying readings PDF
Summary:While the Waterfall Model of software
development is conceptually simple and appealing it
often struggles with the realities of building complex
systems, requiring (near) perfect knowledge at the outset
and a client who never changes his or her mind. Agile
approaches, in addition to using a catchy name, treat
software development as a collaborative and adaptive
process. The ethos of Agile is captured in the Agile
Manifesto (reproduced on the next page).
The Agile Manifesto
The key values of people who practise Agile are:
Individuals and interactions over processes and tools
Working software over comprehensive documentation
Customer collaboration over contract negotiation
Responding to change over following a plan
http://agilemanifesto.org
Agile in KIT206/506
Because Agile is fundamentally a philosophy there
is no one true Agile methodology™, but instead a
large number of methodologies that fit with the
aims in the Manifesto.
Because the progression of topics in this unit is
linear, like the Waterfall Model, you will not practise
many of the specific Agile methodologies (such as
Scrum), but you will
• experiment briefly with user stories as a means of
understanding the requirements of a software
system;
• and engage in pair programming when
implementing your application.
Reading 4: User stories in Agile
Web page: User Stories and User Story Examples by NAME
(see the 6 headings in the accordion view; click each to reveal)
Location: http://www.mountaingoatsoftware.com/agile/user‐stories
Time: 5 minutes approximately
For context: consider reading first three paragraphs of
http://www.mountaingoatsoftware.com/agile/scrum/product‐owner
Summary: Agile’s user stories serve two purposes: requirements
elicitation (which is what the Requirements Specification and
RTM capture) and as an ongoing ‘to‐do’ list in the Scrum
methodology, which we will not be using.
User stories in Agile
A user story is a brief summary of an action that
a user wishes to perform with the system.
They’re often low‐tech, written on small cards.
User
Story
“As a teacher, I can select a student’s entry in a
class list to view details of their results”
As a
I can
So that
Optional reading: Use Cases to User Stories
“Mapping Use Cases to User Stories” in
Agile Software Development 2nd ed, NAME , 2006
Location: starts half way down this page
http://proquest.safaribooksonline.com/book/software‐
engineering‐and‐development/agile‐
development/0321482751/agile‐and‐self‐adapting‐
evolution/226?uicode=utasedu
Time: 2 minutes
Summary: This brief excerpt examines one way to link use cases
to Agile user stories. Even if the process that you employ is not
strictly Agile, this illustrates how a user‐centred approach to
identifying a user’s requirements can help in planning
and in the eventual implementation of a system.
Reverse engineer some user stories
Task: Think of some software or a web service
you use and different activities you use it for.
Write down user stories to describe those
activities. What is your role? What is the
activity? What is the need it fulfils?
(Yes, this is the reverse of a how a user story is normally
generated, since the functionality clearly already exists,
but it should still be possible.)
Writing your own stories
Task: Thinking about the same software or web
service, what’s some action it doesn’t yet
support that would add value for you?
Write down at least one user story to describe it
Document‐driven versus Agile
‘Traditional’ Agile
There is a tension, bordering on incompatibility, between
‘traditional’ approaches to capturing and validating requirements
and the Agile approaches. We cover Agile all too briefly here (and
in greater depth in other units) so that you are aware of some of
the differences.
Which approach you use will depend on the system you are
building, the client and your development team.
Regardless of the name of the methodology you use, we
recommend that you take a user‐centred approach, as promoted by
Agile.
Requirements spec
RTM
Use Cases
Scenarios
User Stories
Scenarios (but not the
same as on the left)
Scenarios
…but not of the Agile variety
Scenarios
A scenario is a formatted description of the steps
required for the completion of a Use Case.
A template is available with this module on MyLO.
Note that the Action – Software Reaction table is the
most important section
Generating scenarios
Given the RTM,
complete the scenario template for each use
case,
– One for every requirement given type SW in RTM
– Only one scenario per use case (even if tempting to create
more than one)
prototype the interfaces for each scenario, and
develop OO Diagrams from each scenario (later
in the unit)
Template scenario p 1/4
Use Case #: Title
Requirement:
Overview:
Preconditions:
Template scenario p 2/4
Scenario:
Action Software Reaction
1.
2.
2.
Scenario Notes:
Template scenario p 3/4
Post Conditions:
Required GUIs:
Template scenario p 4/4
Exceptions:
Use Cases utilised:
Timing Constraints:
We will begin working on scenarios in the first tutorial
Reading 5: Usability
Usability 101: Introduction to Usability,
by NAME
(about 3 pages)
Location:
https://www.nngroup.com/articles/usability‐101‐introduction‐to‐usability/
Summary: Usable systems are learnable (without
referring to a manual), efficient, memorable (easy to pick
up again later), handle errors well, and ideally lead to a
satisfied user.
Although we won’t be undertaking participatory studies
to evaluate the usability of the application you develop, it
is worth familiarising yourself with these common
principles of usability systems. As you sketch
prototype UIs, and specify the sequence of
actions a user will take in each scenario, keep
these principles in mind.
User Interfaces and Interface Prototyping
Clients’ (users’/players’) satisfaction with the
system will predominantly be determined by the
user interface
• So you should always prototype your interfaces
• Divide the system into a number of meaningful
interfaces
• Develop interface prototypes that contain useful,
meaningful content that helps envisage the final
system (these can be done on paper)
• Seek feedback from end users and client
Interface Prototypes
• Develop diagrams of the UI that have a
consistent artistic style across the set of
interfaces and use appropriate UI & design
principles
• Clearly explain each interface and how the
user interacts with each item
• Clearly explain how the user navigates
between the different interfaces
Interfaces (for Scenarios)
As you’ve seen in the template:
• In a scenario every screen is given a name
• Every button, text field, etc. is mentioned
• Draw a draft of each GUI identified as being
required by the scenarios
• Produce executable prototypes of each GUI in
implementation language (optional in this unit
as we are yet to cover C# development)
A brief word on prototyping in
Agile & other methodologies
Reading 6: Prototyping
Section 3.2.1 (4 pages); you may optionally
continue to the end of 3.2 (9 pages) to complete
your introduction to Agile.
in Software Engineering: Principles and Practice, 3rd
ed, by Hans van Vliet, 2008
Location: accompanying readings PDF
Summary: Prototyping is a key part of the iterative
process of Agile and maintains the approach’s focus
on the user and their needs.
UI prototyping (to identify a good UI design rather
than to elicit requirements) is a related but separate
topic, and is part of the process of creating
(non‐Agile) structured scenarios.
Next…
The next module will look at object‐oriented
modelling and design, including using the
Unified Modelling Language’s package, class and
sequence diagrams
Module 2
Object-oriented modelling and design
Part 1: Introduction, overview and readings
KIT206 Software Design & Development
KIT506 Software Application Design & Implementation
Object-Oriented Analysis &
Design with Applications, Booch
et al. (2007), Sections 5.1, 5.2,
5.5, 5.7, 5.8, 6.3
Suggested workflow
Ch 10.2, Software
Engineering, NAME (2008)
Parts of UML Distilled,
Fowler (2003)
2.1 This overview
optional (much more
detailed than Fowler)
UML Diagram
types
Ch 10.3, Software
Engineering, NAME (2008)
2.2 Deriving an OO
model from use
cases & scenarios
Click thumbnail to go to relevant slide
tutorialspoint.com/uml optional
The big picture of object-oriented design
Object-oriented (software) design is the process of modelling real-world
entities (people, books, accounts, etc.) as different classes of objects
Each class has relationships to other classes (a person can have some
books out on loan) and interactions with instances (objects) of other
classes (a person may borrow a book)
This two-week module examines:
• static modelling, which captures the data that describe objects of different classes and the
enduring relationships between them;
• dynamic modelling, which captures the order of actions within each use case;
• how to represent these using the Unified Modelling Language; and (in Part 2)
• how to derive this information from use cases and scenarios
Each class becomes a ‘module’ of a software system; the interactions
between objects of each class help the programmer write the low level
code that does the real work
Our location in the process
Requirements
specification
Requirements
trace matrix
(use cases
identified) Scenarios
: Register : Sale
makeLineItem(quantity)
: SalesLineItemcreate(quantity)
User interfaces (later)
help plan
identify classes,
methods and
interactions
Class diagrams Sequence diagrams
Requirements
(given/assumed)
Design
This module looks at the
diagramming language UML and
then how information in scenario
documents can be used to derive
models for static structure and
dynamic interactions
Reading: Modelling and Objects
Chapter 10 (opening & 10.2, ~7 pages) in
Software Engineering: Principles and Practice,
3rd ed, by Hans van Vliet, 2008
Location: PDF on MyLO
Summary: This reading describes the role of
modelling in software development and how the
notion of the object has become so important in
most software development today.
The Unified Modelling
Language
An overview
UML
• The Unified Modelling Language is so called
because it was formed by the unification of
several competing modelling languages
• Is largely pictorial/diagrammatic, but is still a
language with syntax and semantics
• It includes
1. a large number of different diagrams for modelling
different aspects of a system
2. a large ‘vocabulary’, both in the way each diagram is
drawn and in additional text-based notation that can
be attached to a model
• In this unit we will study and use a subset of the
language
Reading: A first look at UML
Chapter 10.3–4 (~14 pages, many diagrams) in
Software Engineering: Principles and Practice, 3rd ed,
by Hans van Vliet, 2008
Note: 10.3.2 and 10.3.4 are optional
Location: PDF on MyLO
Summary: A first look at UML and some of its more
notable diagram types. UML’s large number of
different diagram types can be bewildering. In this
unit we only use a few of them, but be aware that in
the future you should always ask yourself if another
is best-suited to the task at hand.
Types of UML diagrams
UML diagram
Structure
diagram
Package Class
Component Object
Composite
structure Deployment
Profile
Behaviour
diagram
Activity Use case
State machine Interaction
Sequence
Communication
Interaction
overview
Timing
See also https://en.wikipedia.org/wiki/Unified_Modeling_Language#Diagrams
General kind
of diagram
Diagram type
Diagram we
will use
Diagram we
may use
https://en.wikipedia.org/wiki/Unified_Modeling_Language%23Diagrams
UML Diagrams
Diagram type Models
Package Grouping of classes into packages
Class Classes, their features and relationships between them
Component A componentised view of classes focusing on interfaces
Object Objects and their relationships at a particular moment in time
Composite structure Internal structure of a class
Deployment Mapping of software components to physical hardware
Profile Used to extending UML with new model/element types
Activity Business logic, processes and workflows
Use case Use cases required by anything outside the system
State machine States an object can be in
Sequence Order of messages between objects in a scenario
Communication Similar to a sequence diagram
Interaction overview Combination of Activity and Sequence diagrams
Timing State changes in an object over time
Static (structural) diagrams
• Static diagrams model enduring (constant,
eternal, ongoing) features of a system
• In this unit we make use of the following:
– Package diagrams to model the logical
organisation of collections of classes (these map
to packages in Java and namespaces in C#)
– Class diagrams to model classes of objects, their
data and behaviours, and the relationships
between them
Dynamic (behavioural) diagrams
• Dynamic diagrams model events that take
place over time
• In this unit we make use of:
– Sequence diagrams; and optionally, if you see a
need for them,
– Use case diagrams (although mostly the RTM and
scenario documents are sufficient)
Reading: UML Tutorial
Learn UML: unified modelling language
https://www.tutorialspoint.com/uml/index.htm
Summary: A good overview of UML and how to use
it. Focus your reading on package diagrams,
class diagrams (the essentials)
and sequence diagrams.
https://www.tutorialspoint.com/uml/index.htm
Module 2, part 2…
Part 2 is a self-contained presentation on
that describes how to translate use cases and
structured scenarios into package, class and
sequence diagrams
Module 2
Object-oriented modelling and design
Part 2: Creating a model from use cases
and scenarios
KIT206 Software Design & Development
KIT506 Software Application Design & Implementation
Object-Oriented Analysis &
Design with Applications, Booch
et al. (2007), Sections 5.1, 5.2,
5.5, 5.7, 5.8, 6.3
Suggested workflow
Ch 10.2, Software
Engineering, NAME (2008)
Parts of UML Distilled,
Fowler (2003)
2.1 This overview
optional (much more
detailed than Fowler)
UML Diagram
types
Ch 10.3, Software
Engineering, NAME (2008)
2.2 Deriving an OO
model from use
cases & scenarios
If you haven’t already,
do the precursor steps
to this self-guided
presentation
Quick index
Key model types
• packages, classes & sequences of interactions
Structural modelling
• classes of objects and the packages they’re
grouped into
Dynamic modelling
• uses cases (if you really want to) & sequence
diagrams
Approaches to modelling a
system based on use cases
An important heuristic (rule of thumb)
• Model the static structure first. That is,
identify the different classes of objects and
their relationships to one another
• Then (or at least after starting the above) you
can begin to plan the dynamic interactions
between them for each use case/scenario
– these will become the algorithms implemented by
the system
(And remember that use cases are expressed as Actor-
Action-Subject, as in Customer Purchases Tickets)
1-slide introductions to the three major diagram types we will use are next,
followed by more detailed guidelines for creating them
Package Diagrams
A package is a collection of logically related classes
Use the use cases to identify the packages:
– Packages are generally actors or subjects
– There will also be a View package for all the GUIs identified
in the scenarios (this keeps the user interface separate
from the rest of the system)
A Package Diagram is essentially a large-scale Class
Diagram that depicts all known packages and
associations between them
When developing the model(s) the order in
which package and class diagrams are
developed can be alternated (more later)
An example
Class Diagrams
A class diagram for a particular package is a diagram
that depicts all classes owned by the package and all
associations between those classes
Use the use cases to identify the classes (more soon)
– Classes are generally actors or subjects
Use the scenarios (detailed use cases) to identify the
classes, attributes and methods (their operations)
– Classes and attributes are generally actors or subjects
(nouns)
– Methods are generally actions (verbs)
The View package contains all the classes
for the GUIs that have been identified in
the scenarios (more later in the unit)
An example
Sequence Diagrams
Sequence diagrams provide the level of detail necessary for
implementation
Create a sequence diagram for each scenario
– Use the reaction column of the scenario to identify the methods for
the diagram
– Identify all the classes that the scenario interacts with
– Remember to use the view classes (those that represent the GUI) as
well as domain classes
Indicate the operations (methods) that cause two of the classes
to interact (from the reaction column of scenario)
Include comments in the diagram
(typically what’s in the Action column
of the scenario) to make it clear what
is happening at what time in the
diagram
: Register : Sale
makeLineItem(quantity)
: SalesLineItemcreate(quantity)
An exampleJump to the details
Static/structural modelling
with UML
Capturing the different classes of
objects and the relationships
between them
Structural Analysis
Structural analysis determines:
– what classes exist
– what properties they have
– their relationships to each other
In reality, there is little boundary between the
structural and dynamic analyses:
– Static components will also be discovered during
dynamic modelling, and vice-versa
– So, do not be too concerned as you shift gears
and move to the next phase…
Creating class diagrams
A rough checklist (‘rough’ because order is not
strict):
• Identify Entity objects
– these represent business data
• Identify Boundary and Control objects
– these represent the interface with the user
(or external systems)
• Identify associations and aggregations
• Identify attributes
• Identify inheritance relationships
Entity Objects
• Persistent information tracked by the system
• Typically represent objects in the real world,
or at least concepts
– e.g., a Customer, or his/her Account
– a Staff Member, or the Units he/she teaches
– a Researcher, and the Publications he/she writes
• Activities:
– Noun-phrase approach
– Common class approach
Noun-phrases
• A noun could indicate either a class or an
attribute (or both)
• A verb generally indicates a method
– Be careful to associate a method with the class
that owns the data that will be affected by the
method
• An adjective often indicates a subclass (i.e., a
specialisation), or sometimes an attribute
• Other phrases to look for: “is a kind of”,
“consists of”, etc.
“Entity” object identification
Entities typically model real-world things
• Recurring nouns in use cases
• Real-world activities the system needs to track
• Real-world entities the system needs to track
• Data sources or sinks (e.g., Printer)
Common class modelling
• This approach derives classes from the generic
classification theory of objects
– concept class
– event class
– organisation class
– people class
– places class
Example from RAP
Refer to the “Sample RTM – RAP” under Module 1
Note that many use cases refer to researchers, who may
be staff or students, and their research publications
These give us a starting point for modelling the entities
that the system must represent and hint at the
relationships between them (shown with dashed lines)
SomeClass
Publication
attributes omitted
operations omitted
Researcher
attributes omitted
operations omitted
Staff
attributes omitted
operations omitted
is the author of
refinements of
(more details than)
supervises
Student
attributes omitted
operations omitted
Boundary Objects/Classes
• These classes represent the system interfaces
• Models user interface at a coarse level (not
yet most refined description of our final
interface)
– Why bother if they don’t directly translate to
programming code? So that the rest of the model
can refer to the parts of the system that will
interact directly with the user
• A boundary class is a class that is specifically
designed to live at the boundary of the system
and interact with (external) actors/agents
SomeClass
Identifying Boundary Objects
• Important user interface components
• Forms used to enter data into system
• Notices and messages used to respond to the
user
• Always use client vocabulary (since many
models are used to discuss the design with the
client)
Control Objects/Classes
• Coordinate entity and boundary objects
• Generally no physical counterpart
• Life-cycle usually corresponds to duration of a
use-case or user session
Identifying these:
• One per use-case
• One for each actor in a use-case
• Use clear naming conventions; e.g.
ReportEmergencyController
Control classes are often part of the model-view-controller
(MVC) design pattern that you will see in the next module
SomeClass
Example from RAP
Refer to “Sample Scenarios & UI prototypes – RAP”
available under Module 1
Consider UC8_User_views_ResearcherList, which has
identified a number of different GUI elements that will
arrange information on the screen and with which the
user will interact
We can include these (tentatively) identified views and
the fact that the user will interact with a collection of
Researcher objects to create part of our OO model
SomeClass
Researcher
attributes omitted
operations omitted
ResearcherController
attributes omitted
FilterByName(name: string)
⋅ ⋅ ⋅
ResearcherListView
attributes omitted
operations omitted
List
attributes
omitted
operations
omitted
ComboBox
attributes
omitted
operations
omitted
all researchers *controls
Entity classControl class
(maintains collection of researchers and
can update it in response to user’s actions)
Boundary class
(including predefined
GUI controls)
(you can omit such
predefined GUI
components from
your model)
Identifying Attributes
• Attributes have:
– Name
– Description
– Type (this may be vague at first)
• Likely to be unstable through analysis and
design; don’t try and get them all too early
– Focus on behaviours and responsibilities of classes
(abstraction)
SomeClass
Identifying Attributes
• Any stored state
– Particularly for entity objects
• From the description (scenarios and use
cases):
– Noun-phrase followed by possessive (e.g. “the
description of an emergency”)
– Adjectives (“the emergency description”)
• Also discovered during dynamic analysis
SomeClass
Example from RAP
Refer to both the sample RTM and sample scenarios for
the RAP, available under Module 1
Consider UC16_User_selects_Researcher, which specifies
what the user will see when selecting a researcher from
the list
These details tell us explicitly about most of the attributes
of Researcher objects (common to staff and students)
Researcher
-id: integer
-familyName: string
-givenName: string
-title: string
-campus: Campus
…
-currentStart: Date
-currentLevel: EmploymentLevel
operations omitted
«enumeration»
EmploymentLevel
Student
A
B
C
D
E
Information in the requirements document and RTM
can also indicate new enumerated data types, such as
a Researcher’s employment level
SomeClass
Because staff and students share
attributes like start date, it’s
convenient to include ‘student’
as a level of employment
Identifying Operations: a RAP example
Some operations may be apparent during static analysis
For instance, in the RAP example, the researcher detail
view needs to display a running average of publications
for researchers who are also staff
This is not stored directly in the database, but must be
derived from (calculated using) the staff member’s
collection of recent publications
This suggests that Staff objects should have an operation
to report that staff member’s three year average
Staff
no additional attributes
+threeYearAverage(): float
+performance(): float
Additional operations become apparent during dynamic analysis
SomeClass
Researcher
attributes omitted
operations omitted
Publication
attributes omitted
operations omitted
Class Relationships
• Any dependency between two or more classes
is an relationship
• There are 3 types of relationships:
– Association relationships (Uses)
– Aggregation relationships (Composition)
– Inheritance relationships (Generalisation)
Identifying Associations
• Verb phrases (e.g. “has”, “is part of”, “reports
to”, “includes”)
• Multiplicity may be unclear initially
• Eliminate derived associations (perhaps during
testing)
• Name associations and roles precisely
ClassBClassA
Researcher
attributes omitted
operations omitted
Position
level: EmploymentLevel
…
operations omitted
Publication
attributes omitted
operations omitted
1 has *
occupies *
1
Identifying Aggregations
• Aggregations are when one class contains (or
is associated with) a number of objects of
another class
• If in doubt just use associations
• Verb phrases (e.g. “contains”, “is made up of”)
• Look for common life-cycles
Implementation (covered later) is essentially identical
to associations, so don’t worry! ItemContainer
Staff
attributes omitted
operations omitted
Student
attributes omitted
operations omitted
1 supervises 0..*
Identifying Inheritance
• Probably more a design issue; often over-
emphasised in OO (while it can assist in
reusing code it also can make
understanding a system’s source code
more difficult)
• Noun phrases (“is a kind of”, “is similar to”)
• Specialisation is where a descendant/child
class refines or adds to the abilities and
attributes of its parent
• Generalisation is when common attributes
or abilities are moved upward into a
common ‘parent’ class
Parent
Child
Researcher
id: integer
givenName: string
…
operations omitted
Student
degree: string
operations omitted
sp
ec
ia
lis
at
io
n generalisation
Abstract/Concrete Classes
• An abstract class is a superclass in an
inheritance hierarchy that does not have any
instances
• A concrete class is a class that can have
instances
– Examine each inheritance hierarchy. Ask for each
superclass “Is there an instance of this class in the
domain?”
• At this stage in your modelling career you may
not encounter a need for this distinction
Aggregating classes into
packages
View Model
Package
• Just as a class collects data and behaviour in
one place to
– highlight relationships of interest; and
– hide details from those not interested
• a package is a collection of logically related
classes
Why group classes into packages?
• Provides clarity and understanding of a large
complex system
• Provides abstraction at multiple levels
• Supports version control
• Supports modularity: encapsulation (hide details
from other packages) and containment
Package Diagrams
• Classes within a package can have visibility
restrictions
– Visible only to other classes within package
(private)
– Private visibility hides the details that others do
not need
– Relationships between packages can be nested or
peer-to-peer
• When starting your software modelling career
worry about these issues last
Coupling↓ + Cohesion↑
• In all software there is a desire to
– minimise coupling between separate parts (so that
the details of one can be changed without affecting
the other), yet also
– maximise cohesion (so that many different parts can
work together successfully)
• This also drives decisions about packages
• Use cases can provide criteria to group classes
into packages
• Seek to group classes such that
– Actors in the use cases tend to interact with only small
number of packages
– Actors participating in a number of use cases have
their “use cases” from only a few packages
A process to assess packages
• Get a list of potential packages by extracting
all actors and subjects from the use cases
• Extract as a package the root and branches of
an inheritance hierarchy
• Extract as a package the root and branches of
an aggregation hierarchy
• Extract remaining packages
• Look for “common” packages too (for
example, GUI packages, persistence
(database) interaction, etc.)
Example from RAP
Refer to the RAP documents available under Module 1
There are many ways the various classes could be organised, but there
appear to be four main groups of classes involved in the system:
1. entities that model researchers and their publications
2. controllers that manage collections of researchers loaded from
the database, including which subsets are visible in the GUI
3. a legacy database with which the system must communicate, and
4. view classes for the GUI
These become the packages
SomeClass
Control
uses
Ideally there should be few bidirectional dependencies,
but in this case it is because views pass messages
(triggered by user actions) back to controllers
ResearchDatabase Viewuses
Package name may appear on ‘tab’
or on ‘folder’ (like here), depending
on the modelling tool used
55
Package Diagram
• Why have a package diagram:
– Use the diagram to explain to the customer the
overall view of the system
– It helps validate the packages
Refining static analysis
When the class and package diagrams look
‘complete’
• verify with client that vocabulary is consistent
and correct
• update use cases if necessary
• review every class and association
Dynamic modelling
Transforming scenarios into the
sequences of interactions between
objects in a system
Dynamic modelling
• Dynamic analysis captures events such as
object creation and message passing (method
calls)
• It is the main process by which methods are
assigned to classes
– static analysis will mainly discover classes and
attributes
– This may also lead to additional class relationships
being discovered
UML for dynamic aspects of a system
The dynamic model in UML notation describes
those aspects of a system concerned with:
– time and the sequencing of operations
– events that mark changes
– sequences of events – before/after
– states that define the context for events
– the organisation of events and states
In this unit we use sequence diagrams, but for
interest, we’ll look at use case diagrams too, first
Use Cases
• During analysis, use cases capture the system
requirements by focusing on what the system
does or should do
• A use case diagram can provide a high-level
overview of the functionality of the system and
the actors involved
In this unit the structured scenarios are sufficient,
but if you would like an overall view of the use cases
then consider creating a use case diagram
Use Case Diagram
The system
boundary
Actor; need not be a human, but
is anything outside the system
Note: In UML any term inside
chevrons («») indicates a
‘stereotype’ and conveys
special meaning about what is
labelled. Use case diagrams
can label relationships
between use cases with:
«include», meaning that the
endpoint happens at some
time during the starting use
case; and «extend» meaning
that the ‘starting’ use case
adds additional steps to the
one at the end of the arrow
Sequence Diagram
A Sequence Diagram (a kind of interaction
diagram) is a graphical representation of the
interactions between objects arranged
– with some time information required to
implement a use case
– and the term time used in an ordering sense
(rather than elapsed time on a clock)
Events, not operations
Sequence diagrams show objects and their
messages
• A sequence diagram is “simply another way
to represent a communication diagram”
(Booch)
• Focus is on events, not operations
– real-world example: a car stops over a metal
sensor at a traffic light (the event) which triggers
a lot of internal operations (that we don’t see)
inside the control box at the side of the road
Sequence Diagram
• You need the beginnings of an object model (i.e.,
some sense of what objects will exist at different
points in time) to do sequence diagrams
• Sequence diagrams can be used to determine
operations for classes, and new relationships
: Register : Sale
makeLineItem(quantity)
: SalesLineItemcreate(quantity)
Lifeline; shows
when object comes
into existence
A box on a lifeline is
when that object’s
operation is executing
These objects are anonymous (only the class is shown),
but if necessary to disambiguate between two objects
of the same class a name can be given, as in ‘s : Sale’
Creating sequence diagrams
• Identify all actors and candidate objects from
use case/scenario
• For each path through the scenario (including
alternatives and exceptions), identify the
object interactions involved
– CASE tools / sticky notes / CRC cards are all
suitable aids for this
• This identifies methods and classes, and also
redundant objects and relationships
(there must be a relationship in order to send a
message)
An example (taken from a textbook)
1. Sales operative takes customer number and enters it on
the screen
2. Customer details are retrieved and displayed
3. Sales operative confirms details, and ticks a confirm box
4. Sales operative enters order details
5. Sales operative enters delivery details
6. Sales operative requests that the order is created
Example (continued)
: OrderEntryScreen: SalesOperative : Customer
« »
: OrderCreator
« »
: Order
: Delivery
Another example
• Start simple, then elaborate
The following example is for a computer aided
design system. In the use case an Engineer
wants to place a ‘facility’ (a factory perhaps) in
the design she is working on
Start simple…
: MainScreen: Engineer
…then elaborate and add details
: MainScreen
: Engineer
: EditControl : Site
: Facility
« »
An example from the RAP
Consider the structured scenario for
UC16_User_selects_Researcher, available in Module 1
Action 1 describes an initial stimulus from the User (an
actor) that triggers a lot of interaction between
application objects (actions 2 and 3 are omitted from this
diagram to reduce complexity)
As in the engineering tool example, we can start simple…
: ResearcherListView: User : ResearcherController : ResearcherDetailView
LoadResearcherDetails(id)
select entry
SetModel(r: Researcher)
An example from the RAP
…then elaborate, adding more objects and more
operations that define their interactions
: ResearcherListView: User : ResearcherController : ResearcherDetailView: DbAdapter
r : Researcher
LoadResearcherDetails(id)
select entry
SetModel (r: Researcher)
LoadAllDetails(id)
LoadResearcher(id)
«create»
r : Researcher
Performance()
performance
request other
properties
Final words
• Class diagrams model the different kinds of object in a
system, be they part of the GUI, business entities or
controllers implementing business logic
– they are the actors and subjects in use cases; the actions
in use cases become their methods
• Package diagrams model the higher-level organisation
of classes into related groups; they help manage
complexity and reduce the likelihood of errors by
isolating these tightly-related classes from other parts
of the system
• Sequence diagrams model the details of scenarios and
ultimately guide software developers when they
implement a system in code
SomeClass
View
:UI :Model
get()
In upcoming tutorials you will practise creating all three of these
Module 3
Design patterns
KIT206 Software Design & Development
KIT506 Software Application Design & Implementation
What is a design pattern?
NAME (speaking about civil engineering)
described patterns thus:
Each pattern describes a problem that occurs over and
over again in our environment, and then describes the
core of the solution to that problem, in such a way that
you can use this solution a million times over, without
ever doing it the same way twice
In software it is reuse of an approach (rather than code)
Collections of patterns describe problems and solutions,
including trade-offs and consequences (not all of which
are described in these slides)
Reasons for using patterns (briefly)
They can
• provide examples of good design and implementation
• provide a shared vocabulary
• help understand library or framework structures
• promote low coupling, high cohesion, flexibility and extensibility
Often exchange inheritance for composition
Program to an interface, not an implementation
Delegate responsibilities whenever possible
Separate that which changes from that which doesn’t
Suggested workflow
Section 12.5, Software
Engineering, NAME (2008)
Chapter 8 of Object-Oriented
Software Engineering Using
UML, Patterns, and Java,
Bruegge & Dutoit (2009)
Skim read these
slides first
More detailed summary
of a subset of patterns
Appendix A (Design Patterns)
from Object-Oriented Software
Engineering Using UML…,
Bruegge & Dutoit (2009)
The rest of these
slides as a summary
(ongoing) Design Patterns
Reference Cards (on MyLO)
Click thumbnail to go to relevant slide
Reading: Introducing Patterns + MVC
Section 12.5 (5 pages) in
Software Engineering: Principles and Practice,
3rd ed, by Hans van Vliet, 2008
Location: PDF on MyLO
Summary: This reading provides a brief
introduction to software design patterns and
describes one of the most useful for desktop
applications: model-view-controller
Reading: Reusing Pattern Solutions
Chapter 8 (equivalent to 25–29 pages of text) in
Object-Oriented Software Engineering Using UML,
Patterns, and Java, by Bruegge & Dutoit (2009)
Location: PDF on MyLO
Summary: Although this reading is long and a bit
heavy-going in parts, it covers some useful ideas in
software reuse and patterns. Dark orange
annotations indicate which parts should be read,
which are optional, and which should be skipped.
(Note that the examples are in Java, not C#)
What are the patterns?
We’ll consider some of the 23 patterns
identified by the authors of 1994’s Design
Patterns: Elements of Reusable Object-Oriented
Software, by Gamma et al., plus the model-
view-controller pattern that underpins GUI
applications
The authors of Design Patterns have often been
referred to as the Gang of Four (GoF); if you see
a reference to GoF elsewhere it is probably to
these influential authors
https://en.wikipedia.org/wiki/Design_Patterns
Important patterns
MVC: separating presentation from input from data in GUIs
Abstract Factory: flexible object creation
Factory Method: a variant of Abstract Factory
Adapter: wrapping up legacy code and systems
Observer: event-driven programming beyond GUIs
Strategy: flexible replacement of behaviour at runtime
Command: multiple ways of triggering the same action
Singleton: enforcing that only one instance of an object ever exists
Iterator: processing collections of different types (built-in nowadays)
These are some of the most useful patterns right now, although you won’t be applying
all of them in this unit. Each block links to the relevant slide. All below MVC are part of
the 23 ‘classic’ design patterns by the GoF.
Model-View-Controller
Problem: Overly complex monolithic classes for
managing and displaying information in a GUI
Pattern: Rather than having one class that knows the
data, knows how to present it visually and knows how
to handle events, split these three operations across
different classes
Each component can be simpler because it is only
concerned with one particular aspect of the GUI; it
also makes it easier to change the UI or model
This is an archetypical example (the relationships aren’t exactly like those shown)
GUI
+display()
Controller
+handleInput()
Model
+getState()
+setState()
modifies
sends events to
notifies
displays
The GoF’s 23 Design Patterns
Purpose
Creational Structural Behavioural
Scope
Class
Factory Method Adapter Interpreter
Template Method
Object
Abstract Factory
Builder
Prototype
Singleton
Adapter
Bridge
Composite
Decorator
Façade
Flyweight
Proxy
Chain of Responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor
Table 1.1 from Design Patterns: Elements of Reusable Object-Oriented Software by Gamma et al. (1994)
https://en.wikipedia.org/wiki/Design_Patterns
Creational Patterns
Objects are created by invoking class
constructors, but this basic pattern of
instantiation essentially requires that the class
requesting the creation knows ahead of time
which class it needs to create
Creational patterns reduce this dependence
Abstract Factory
Problem: Need to create objects that all implement a particular
interface and would like actual class to vary as needed, but the
instantiation step requires that we know which concrete class we are
creating ahead of time
Pattern: Define an abstract superclass factory that is responsible for
creating the objects we require. Subclasses of this factory are tailored
to produce different kinds of objects
Provides an interface for creating families of related or dependent
objects without specifying their concrete classes
Variant of: Factory Method
Factory Method
Problem: Need to create objects that all implement a particular
interface and would like actual class to vary as needed, but the
instantiation step requires that we know which concrete class we are
creating ahead of time
Pattern: Alternative to Abstract Factory, where top-level factory is
abstract and has a template method that is overridden by a subclass
Good when there are common tasks surrounding object creation but
one step needs to change depending on the type of object
Variant of: Abstract Factory
Uses: Template Method
Builder
Problem: Class constructor has many parameters, so
require many alternative constructors for all the
different ways in which could create it
Pattern: Use a number of different builders that can
each create part of a new object (i.e., setup some of its
attributes)
Alternative to: Abstract Factory and Factory Method
Prototype
Problem: Abstract Factory pattern overly complex for
current problem or cost of creating an object from scratch
is prohibitively expensive
Pattern: Specify the kinds of objects to create using a
prototypical instance, and create new objects by copying
this prototype
Requires that the prototype declares an interface for
cloning itself (MemberwiseClone() in C#, clone() in Java)
NAME : Only ever want one object of a particular
class
Pattern: Hide constructor and provide a static (class
level) method to access a single, private instance
May be suitable implementation for a factory object
Be careful about overusing, since it runs counter to
principles of object-orientation
Singleton
-static uniqueInstance
-singletonData
+static instance()
+singletonOperation()
Structural Patterns
Flexible methods of connecting objects together
that often make it easier to replace parts of the
structure
Adapter
Problem: Have a legacy (or third-party) class
whose interface cannot be changed but is not
compatible with other parts of the system
Pattern: Create an adapter class that knows how
to interact with the legacy class and presents
the expected interface to the rest of the system
Composite
Problem: Would like to treat a group of objects as if
they are actually one
Pattern: Have a top-level abstract ‘component’
from which low-level and composite components
are derived
Common issue (and solution) in GUIs, where we can
construct reusable composite components from
low-level components
Decorator
Problem: Need to attach new responsibilities or
behaviours to an object dynamically
Pattern: Have objects that can ‘wrap up’ objects of other
classes to provide this added or different functionality
Common in IO, with simple IO classes able to be wrapped
by ones that do additional processing of the information
being read or written
Also used in GUIs, with components that contain others
to provide additional functionality
Proxy
Problem: Operations on a particular class are potentially
memory intensive, unsafe, or take a long time
Pattern: A proxy object, that implements the same interface
as the actual object, can control access to the real class,
handling requests asynchronously
Proxy can act as single window for a service that is provided
by different objects over time. Client does not need to know
identity of server object
Proxy can accept service request before server object exists
Façade
Problem: Want to reduce apparent complexity
of a subsystem and reduce the number of points
of dependency on its interface
Pattern: Provide a single point of contact with
the subsystem that presents a simpler interface
Other structural patterns
Pattern Description Notes
Bridge Decouples the actual
implementation of a class’s
behaviour so its external interface
and the behaviour can both vary
Similar to, but more confusing
than, the Strategy behavioural
pattern
Flyweight Share common data so that
numerous (but possibly small)
objects are not duplicated in
memory
Still occasionally useful, depending
on the problem being solved;
represents an optimisation of a
design
Behavioural Patterns
Allow programs to implement different
behaviours with little or no change to existing
class code, and help “code organisation” so that
parts of the code dealing with independent
issues do not clutter each other
Template Method
Problem: Want to define an algorithm in general terms,
so subclasses can easily customise it. Many operations
have a common structure, but differ in parts depending
on the class
Pattern: Abstract superclass with algorithm method in
terms of (class specific) abstract methods
Subclasses need only override the abstract methods
Related to: Strategy
templateMethod() calls
subMethod() at some
point in its execution
Observer
Problem: Many objects may want to monitor another for
changes, while maintaining low coupling
Common in GUIs
Pattern: Observing objects register themselves with
source object; source invokes same method on all when it
changes
Essentially this is event-driven programming
Chain of Responsibility
Problem: Have a number of possible ‘responders’ to an ‘event’ (or
data that needs processing) and need an efficient way of handling a
variety of such ‘events’
Pattern: A client sends a command without knowing the object or
objects that are responsible to act the command. Command receivers
are chained together. The first object in the chain able to respond to
command executes it (processes the data, etc.), otherwise objects in
the chain pass the command on to the next in the chain. (A command
may exit the chain without being run)
Many GUI event handling models and exception handling models work
this way
Command
Problem: Need different ways of triggering the same action (e.g.,
toolbar icon, keyboard, menu, undoing or repeating previous
commands) but want to reduce duplication of code to handle
these
Pattern: A client creates a command containing the action to be
performed and a reference to the object who will do the action.
Commands passed to a command manager that executes a
command by invoking a preset method in the command (object)
Strategy
Problem: Need an object to be able to change its
behaviour dynamically without cumbersome use of
control structures in its code
Pattern: Define a family (hierarchy) of algorithms
with a common interface. The class that needs to
change its behavior selects (or is told to use) a
particular strategy as needed
Related to: State (not included here as very similar)
Visitor
Problem: Need to be able to pass different behaviour
as an argument to a method without knowing the class
providing that behaviour until runtime
Pattern: Allow the elements (to be processed) to
accept a ‘visitor’, whose runtime type will vary
Obviated by: Any language with functions as first class
data types, which includes C# and Java (version 8)
https://en.wiktionary.org/wiki/obviate#Verb
Other behavioural patterns
Pattern Description Notes
Interpreter Essentially a parser Highly specific
Iterator Access elements of an aggregate
object sequentially without
knowing its internal representation
Built-in to modern languages
Mediator Program objects do not interact
directly but instead via a mediator
object, which can alter the
interactions dynamically
Can be relevant in GUIs to
coordinate the properties of
groups of components
Memento Persist and restore an object’s
internal state without requiring it
to make that state public
Obviated by object serialisation
and object-relational mapping
technologies
State Cleanly allow object’s behaviour to
vary depending on its state
Really a variant of the Strategy
pattern where the object is in
complete control over which
strategy is currently employed
Module 4: Object-oriented
programming with C# and .NET
Part 1: .NET and C# basics
(summary slides)
KIT206 Software Design & Development
KIT506 Software Application Design & Implementation
First
1. Do the online readings (the Module 4, part 1
overview document indicates what to read
and which activities to do)
2. No, really go and do the readings and
activities, and then
3. Continue reading from here
The .NET Framework
Jump to C# Basics
.NET
• .NET is a platform for developing managed
software, which means
– the file produced by the compiler is not an executable
binary but it is an assembly
– an assembly contains intermediate language (IL) and
metadata (the intermediate language serves a role
similar to Java bytecode, although the two are not
compatible)
• .NET supports a number of different
programming languages that are all compiled to
the same IL
*.cs
Source Code
C# Compiler
*.dll or *.exe
Assembly
Common Language Runtime (CLR)
• C# applications are compiled to assembly and
executed by the CLR (i.e., by a virtual
machine)
• CLR features include
– .NET Framework class library support
– Debugging
– Execution management (e.g., to ensure security)
– Garbage collection (automatic reclamation of
unused memory)
Schematic of CLR execution process
.NET Base Class Library (BCL)
• This is the core library of classes used by C# (and
other languages that can run within the CLR)
• Contains a large number of reusable classes
• It is organised into Namespaces (if you have a
Java background these are similar in purpose to
packages, but the mechanism for implementing
them is different)
• Some example namespaces are:
– System
– System.Windows
– System.Linq
• You may also encounter the Framework Class
Library (FCL), which is a superset of the BCL
Common Type System
• .NET supports multiple programming languages,
but these share a set of common data types
• This is referred to as the Common Type System
(CTS)
• All these languages use the CLR and reuse the FCL
(the larger library that includes the BCL used by
C#)
• In order for this to work the types in each
programming language must be compatible; this
binary compatibility is called the CTS
Common Language Specification (CLS)
• The CLS is a common set of language features
to which every .NET language must adhere
• This allows reusable modules to be written in
one language (e.g., C#) and used in programs
written in another language (e.g., VB.NET)
• You can still use non-CLS features in your
modules; they just must not be exposed to the
public interface of your module (i.e., the
public methods in your classes)
C# Basics
A minimal application (next)
Expressions and Statements
Reference types and value types
String operations
Arrays and Enums
Select a topic above to jump to that section
A minimal console application
‘Hello World’
See https://msdn.microsoft.com/en-us/library/k1sx6ed2.aspx
// A Hello World! program in C#
using System;
namespace HelloWorld
{
class Hello
{
static void Main()
{
Console.WriteLine(“Hello World!”);
// Keep the console window open in debug mode
Console.WriteLine(“Press any key to exit.”);
Console.ReadKey();
}
}
} Each time you learn something new, no matter
how small, try it out in an application like this
https://msdn.microsoft.com/en-us/library/k1sx6ed2.aspx
https://msdn.microsoft.com/en-us/library/k1sx6ed2.aspx
Expressions & Statements in C#
Operators
• Unary Operators
– Minus operator (-), negates variable’s value
– Increment operator (++), increments variables
value by 1, can be pre or post, e.g.:
int index = 5;
int count = ++index; //count = 6, index = 6 OR
int count = index ++; //count = 5, index = 6
– Decrement operator (–), decreases variable’s
value by 1; can be pre or post
– Logical complement operator (!), inverts a boolean
expression, e.g. !true == false
Operators
• Binary Operators
– Includes all typical mathematical operations, e.g.,
multiply (*), divide (/), modulus (%), addition (+),
subtraction (-)
• Relational Operators
– Includes all typical comparison operations, e.g. equals
(==), does not equal (!=), less than (<), greater than (>)
• Logical Operators
– The important ones are Boolean AND (&&), Boolean
inclusive OR (||) and Boolean exclusive OR (^)
Compound operators
• A compound operator is a combination of an
assignment operator (i.e., =) with an
arithmetic operator (e.g., +)
– int total = 7;
total += 3; //total == 10
• Some examples
– multiply (*=), division (/=), addition (+=),
subtraction (-=)
Ternary operator
• A ? B : C
• A conditional expression that returns part B if
A is true, part C otherwise. Consists of
A. a boolean expression
B. expression that is evaluated if A is true
C. expression that is evaluated if A is false
For example,
int age = 40;
string bestDoctorWho = age > 20 ? ” NAME “: ” NAME ”
Type and conversion operators
• is operator: checks to see if a variable is of a
given type (e.g., s is string)
• as operator: attempts to convert a reference
type (i.e., an object) to another type (e.g., o as
string)
• sizeof operator: returns number of bytes a
type can hold (e.g., sizeof(int))
• typeof operator: returns a Type object which
holds information about a type (e.g.,
typeof(int))
Statements
• Statements cause a change in the program’s
current state; they do something
• A statement MUST end with a semicolon (;)
• A statement can span multiple lines
Blocks and scope
• Blocks are delimited by curly braces {…}
• Blocks specify the boundaries of many
language elements, e.g., classes, methods,
structures, etc.
• Blocks also specify scope. Any variables
declared within a block are only known and
accessible within that block
if statement
Conditionally execute a block of code
Three ‘variants’:
Execute or skip
statements
if (boolean expression)
{
statements to
execute if true
}
Execute one or another
block of statements
if (boolean expression)
{
statements to
execute if true
}
else
{
statements to
execute if false
}
Decide among several
alternatives
if (boolean expression)
{
statements to
execute if true
}
else if (boolean expression 2)
{
statements to execute
if that was true
}
else … //and so on
switch statement
switch selects a set of statements to execute by
matching an integer or string value against a set
of possible values
switch (expression)
{
case value1: statement(s) break;
case value2: statement(s) break;
case value3: statement(s) break;
default : statement(s) break;
}
switch statement example
//Some menu that asked the user to select their favourite Doctor
Console.Write(“You indicated your favourite Doctor Who is “);
switch (choice) {
case “A”: Console.WriteLine(” NAME “); break;
case “B”: Console.WriteLine(“Jon Pertwee”); break;
case “C”: Console.WriteLine(” NAME “); break;
case “D”: Console.WriteLine(” NAME “); break;
default: Console.WriteLine(“none of them!?”); break;
}
while loops
Continually executes a group of statements
while the expression remains true
while (boolean expression)
{
…
}
do while loops
Like a while loop but always executes the loop
body at least once
do
{
…
} while (boolean expression);
for loop
Combines an initialisation step, boolean test and increment
step into a compact structure. Used most commonly to
execute a set of statements a fixed number of times
for (initializer; boolean expression; update)
{
…
}
• The initialiser is executed once, then the boolean
expression is evaluated
• After the set of statements has run, the modifier is
executed and then the boolean expression is evaluated
again
for (int i = 0; i < 10; i++)
{
Console.WriteLine("i is now {0}", i);
}
foreach loop
Iterates over the elements of a collection (there are
many different kinds) or an array
foreach (type identifier in collection)
{
…
}
• For example,
int[] a = { 1, 2, 3, 4 };
foreach (int i in a)
{
Console.WriteLine("Current element is {0}", i);
}
Other statements
• goto: jump to a label in the code (do not use)
• break: jumps out of any decision or loop
structure (use only in switch)
• continue: skips to next iteration in a loop (do
not use)
• return: return a value from a method or
immediately leave a method
Reference types & value types
Reference vs value types
• The .NET type system is divided into reference types
and value types
• There are differences in memory allocation and
assignment behaviour; correct use improves
application performance and reduces errors
• A reference type has a value that is a reference to an
object in memory
• A value type has a value that contains the object itself
• Additional reference types are declared by using the
class keyword
• Additional (structured) value types are declared by
using the struct keyword
Memory allocation
• Application memory is divided into the ‘stack’ and
the ‘heap’
• The stack is used to hold local variables and other
information about each method (function) that is
executed. Each method call goes on the stack
and, when finished, is removed from the stack.
• Reference type objects are always allocated on
the heap
• A reference type variable will either hold a
reference (pointer) to an object on the heap or it
will be set to the special value null
Value types and memory allocation
• A value type variable can either be allocated on
the stack or on the heap
• The CLR has a stack for keeping track of the
execution path from the entry point to the
currently executing method in an application
• Value type variables passed as arguments to
methods and local variables in a method are
pushed onto the stack
• Value type variables declared as fields of a class
are stored on the heap
• A value type will always hold the object that is
assigned to it
References and assignment
Because reference types (which make up the majority of
data types applications deal with) point to the location of
an object on the heap, assignment does not copy the
object’s value, only its location. For example, (continued
over next slides)
Customer cust5 = new Customer();
cust5.Name = " NAME ";
Customer cust6 = new Customer();
cust6.Name = " NAME ";
cust5
cust6
Customer()
{ Name = " NAME "}
Customer()
{ Name = " NAME "}
References and assignment
cust5 = cust6;
cust5.Name = " NAME ";
cust5
cust6
Customer()
{ Name = " NAME "}
Customer()
{ Name = " NAME "}
cust5
cust6
Customer()
{ Name = " NAME "}
Customer()
{ Name = " NAME "}
Manipulating strings
C# string type
• Represents a string of characters
• Is a reference type
• Is immutable; it can’t be changed once
created
• The string type is sealed; it can’t be derived
from
• These two features enable the CLR to be
efficient and secure
String methods
• The Format() method is useful for formatting a
string (including the values of other variables)
• Useful methods for comparing strings include:
– Compare (culture/language aware comparison)
– CompareTo (lexicographic/dictionary comparison
based on characters in two strings)
– Equals (are two strings equal/contain the same
sequence of characters; can be requested to
perform differing comparison tests)
• Three useful methods for copying a string:
Copy, CopyTo, Clone
String methods
• Useful methods to inspect strings include:
– StartsWith
– EndsWith
– Contains
– IndexOf
– LastIndexOf
– SubString
– Length
• Useful methods to modify a string (i.e., return a new string with the modification
made) include:
– Insert
– Remove
– Replace
– ToLower,
– ToUpper
– Split
– Join
Arrays and Enums
Arrays
• Arrays hold fixed-length, indexed lists of objects
• After an array has been initialised its size cannot
be changed
• All arrays inherit from the System.Array class
• Some useful functions are:
– GetLowerBound
– GetUpperBound
– BinarySearch
– Sort
– IndexOf
– LastIndexOf
– Reverse
Array Dimensions
Arrays can be one-dimension, multidimensional or jagged
//single
string [] countStrings = new String[3];
//3 dimensions
int [ , , ] stateSpace = new int[2,5,4];
//A jagged example
decimal [] [] monthlyVariations = new decimal [12][];
int jan = 0; int feb = 1; … int dec = 11; //should be enum
monthlyVariations[jan] = new decimal [31];
monthlyVariations[feb] = new decimal [28];
monthlyVariations[dec] = new decimal [31];
Enums
• Enums are a list of strongly typed constant values
enum Months {Jan, Feb, Mar, Apr, May, Jun, Jul,
Aug, Sep, Oct, Nov, Dec};
Months currentMonth = Months.Nov;
• System.Enum gives you a number of useful
methods to manipulate Enums:
– Parse
– GetName
– ToString
– ToObject
– GetUnderlyingType
– IsDefined
Enums with foreach
• The foreach loop is well-suited to looping through
Enum values
foreach (var month in Enum.GetValues(typeof(Months)))
{
Console.WriteLine(month);
}
• The switch statement is well-suited to doing something
different for each value of an Enum
switch (currentMonth)
{
case Months.Jan: statement(s) break;
case Months.Feb: statement(s) break;
…
case Months.Dec: statement(s) break;
}
End of part 1 summary slides
Module 4: Object-oriented
programming with C# and .NET
Part 2: Object-orientation in C#
(summary slides)
KIT206 Software Design & Development
KIT506 Software Application Design & Implementation
Topics
Organising code with namespaces
Basic Object-orientation in C#
Inheritance
Methods
Abstract classes & interfaces
Delegates & Events
Advanced topics (not essential right now)
Naming and Organising Types
with NAME
• The purpose of namespaces is to help organise code
and reduce conflicts between names
• C# Namespaces and Java Packages are similar but
there is a significant difference: there are no rules
forcing C# namespaces to conform to the directory
placement of the files
• C# namespaces are logical rather than physical
– Can have more than one namespace in a source (.cs) file
– Can nest namespaces within a single file (in Java it is the
directory structure that is nested)
Namespace Directives
• C# has two namespace directives
using: This directive permits a method call without
using the fully qualified name. For instance,
using System;
means that we can write Console.WriteLine()
instead of System.Console.WriteLine()
alias: This directive allows a program to have
another name for a namespace (e.g. make it
shorter), as in
using Cons = System.Console;
creates an alias (Cons) for Console
Creating Namespaces
• Use the keyword namespace followed by
whatever you want to call it
• Namespaces can be nested
• If you create a project in Visual Studio, it
normally calls the namespace whatever name
you gave to the project
namespace AnExampleNamespace
{
//code, normally containing some classes
}
Basic Object-orientation in C#
(including some OO concepts with
which you should already be familiar)
Object Members
• Objects should be self-contained with a single purpose
• Use the class keyword to define a new class of objects
• An object (i.e., its class definition) can have the
following members:
– fields (the data that describe each object)
– constructors (initialisation code)
– destructors (clean up code before object’s memory is
reclaimed by the garbage collector)
– methods (named blocks of code)
– properties (concise way of defining getters and setters)
– indexers (allow indexed access to an object; not covered
here)
– events (to which listeners may subscribe; more later)
Instance & static members
• Each member of an object can be either an
instance member or a static member
• When an object is created (instantiated), it
exists with its own set of attributes and
behavior
• If the static keyword is used during definition
for a member then every instantiated object
refers to the same copy of the member
Fields
• Fields are members of a class
• They are defined inside a class or property
• They can be initialised when declared or later
Constants
• When the value of a field is known ahead of
time and won’t change you can create a
constant
• It will not change during execution
• The value is known at compile time
• Use the keyword const
• e.g., const int DaysPerWeek = 7;
Readonly fields
• Similar to constants and can’t be modified
after instantiation
• Initialised at runtime
• Use the keyword readonly, as in:
public readonly DateTime executionDate = DateTime.Now;
Properties
• Not available in Java
• A C# property enables you to protect access to
the state of your object
• Similar to fields but operate like methods
• They have get and set accessor methods that
have any logic you want to define, including
checking that the new value is value or notifying
other objects of the change
• These methods can be auto-implemented, e.g.,
public int Rating { get; set; }
Property example
private string description;
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
static void Main()
{
WebSite site = new WebSite();
site.Description = "cool.site";
string desc = site.Description;
}
Inside the set part of a property
definition the identifier value refers
to the value being assigned to the
property
In the example above, the value
variable would be equal to “cool.site”
Indexers
• (Note: It is not necessary to understand this
feature right now)
• Indexers let you build objects that can be used
like arrays
• Cross between array, property and method
• They have get, set accessors
• They are useful to prevent accessing out of
range values
Partial Types
• Partial types allow you to divide the definition of
a single type into multiple parts (files)
• Primarily used to separate machine-generated
code from code that you work with
• Use the keyword partial in front of the word class
• At compile time, they are compiled into a single
type
• Most of the time you do not need to deal with this
manually; the GUI Builder will create the separate
files for you
Inheritance
(including some OO concepts with
which you should already be familiar)
Inheritance
• Inheritance is an object-oriented principle
relating to how one class, a derived class, can
share the characteristics and behaviour from
another class, a base class
• This is described as an “is a” relationship
• The derived class is a specialisation of the
base class
• A sealed class is a class that can’t be derived
from; use the keyword sealed
(the equivalent in Java is declaring a class as final)
Example
public class Contact
{
public string Name { get; set; }
public string Email { get; set; }
public string Address { get; set; }
}
public class Customer : Contact
{
public string Gender { get; set; }
public decimal Income { get; set; }
}
Customer
Gender : string
Income: decimal
Contact
Name : string
Email : string
Address: string
Accessing members
Access modifier Accessability
public Accessible by everything (with a reference to the object)
private Only accessible to members of the same class (but not
derived classes)
protected Only accessible by members of the same class and any
derived class
internal Restricts access to code within the same assembly
(compiled intermediate language code)
Redefining a base class member
• Some derived class members have the same
name as a base class member
• When using an instance of the derived class
you invoke the derived class specialised
behaviour instead of the base class behaviour
• This is called “hiding” the base class behaviour
• Hiding a base class member generates a
warning from the compiler (because it may
have been unintentional)
Hiding, versioning, overriding
• Hiding is where a base class has a method that you hide
by defining a method with same name in derived class
• Versioning is where you use the keyword new to indicate
you are deliberately hiding the base class member (this
removes the warning as you have indicated the hiding is
deliberate, not accidental)
• Overriding is when you use the keyword override to
indicate you are overriding a virtual member of a base
class (virtual members are methods that have a header
but no implementation)
• If you want to access the base class member use the
keyword base
Implementing Methods
Defining methods
• Methods contain the majority of an object’s
behaviour
• Method declarations have the format:
[modifiers]
{
[statements]
}
Method Parameters
• C# offers a great deal of flexibility when declaring
the parameters of a method
• These allow the method designer to convey the
intended use of a parameter and to have this
enforced by the compiler
• Parameters may be:
– Value (the default)
– Ref
– Out
– Params
These are each covered next
Value Parameters
• Value parameters are the default and are passed by
value: a copy of the variable is made and given to the
method
• The original copy from the caller is not changed
• But any reference types can still be altered since it is
the reference that is copied; both the copy and the
original still ref to the same object
• As usual, an argument passed into a method must be
the same type as the specified parameter or must be
implicitly convertible to that type (e.g., an int can be
converted automatically to a double)
public void Example(int a)
{
a = 5;
}
int i = 10;
Example(i);
Console.WriteLine(i); //prints 10
Ref Parameters
• Modifying a ref parameter within the body of
a method also changes the original variable
passed in as an argument
• Ref parameters must be assigned (have a
value) before passing them to a method
• Ref parameters enable you to pass a value in
and out of a method
public void Example(ref int a)
{
a = 5;
}
int i = 10;
Example(i);
Console.WriteLine(i); //prints 5
Out Parameters
• Out parameters indicate a parameter that can only be passed
out of a method. They provide a way of returning multiple
values (in multiple out parameters).
• The method may still use return to return a single value as
well
• Out parameters do not need to be assigned before calling the
method
• Any attempt to access the out parameter before it is assigned
within the method gives a compile-time error, so any value
they have prior to calling the method cannot be used inside it
• Out parameters must be assigned before the method returns
public void Example(out int a)
{
a = 2;
}
int i;
Example(i);
Console.WriteLine(out i); //prints 2
out keyword is required in call; essentially the caller is
acknowledging that the parameter is an out parameter
Params Parameter
• The purpose of a params parameter is to allow
methods that will accept a variable number of
arguments
• An example is Console.WriteLine, which can take
any number of parameters
• The argument for a params parameter can be
either an array or a variable number of
parameters of the correct type
public void Example(params int[] a)
{
foreach (int val in a)
{
Console.WriteLine(val);
}
}
Example(1, 2, 3, 4); //prints each on new line
Overloading methods
• Overloading enables you to define multiple
versions of a method with the same name
• Objects often have multiple methods that do the
same thing, but they can be called with different
parameters (different types)
• Often useful when the overloaded methods have
the same return type (supporting multiple inputs
to generate the same type of output) but the
return types do not have to match
public int Example(int a)
{
return a * 2;
}
public int Example(double d)
{
return (int)(d * 2);
}
Type Conversion
• C# is strongly typed and protects you from accidental
assignment of one incompatibly typed variable to
another
• C# conversions can be classified as either implicit or
explicit
• Implicit conversions occur automatically, without
special method calls or cast operators
• Explicit conversions are required when something
may go wrong and require cast operators, such as
int a = (int) 3.14159 //a gets the value 3
Partial Methods
• Just as you can have partial types you can also
have partial methods
• A method consists of a defining part and an
implementation part
• You can put the defining part (the header line
followed by 😉 in one file, and the
implementation part in another file
• Typically arises when using GUI Builders that
define the method header but leave the
implementation to you
Implementing Abstract Classes
and Interfaces
Abstract Classes
• Abstract classes are a special type of base
class
• They have abstract members: members with
no implementation
• All classes derived from the abstract class
must implement the abstract members (or
themselves also be abstract)
• An abstract class can not be instantiated
Abstract Classes
• To identify a member as abstract, use the
keyword abstract as the first modifier
• In a derived class when you want to provide
the implementation for an abstract member
use the keyword override
abstract class Alpha
{
public abstract void SomeAction();
}
class Omega : Alpha
{
public override void SomeAction()
{
Console.WriteLine(“Action taken”);
}
}
Interfaces
• Interfaces are specifications defining the type of behaviours a class
must implement
• While abstract classes may contain some implementation, but
interfaces cannot
• A derived class must implement all members defined in an interface
• To define an interface instead of the keyword class use the keyword
interface
• Interfaces can inherit from multiple interfaces (unlike classes)
• All the members of an interface have slightly different methods of
declaration (from a class member); consult the MSDN documentation
interface IExample
{
void SomeAction();
}
class Alpha : IExample
{
public void SomeAction()
{
Console.WriteLine(“Action taken”);
}
}
Event-Based Programming
with Delegates and Events
Delegates
• Delegates and events are used to perform
event-based programming in C#
• A C# delegate is a type safe method reference
• With delegates a program can dynamically call
different methods at runtime
• The primary purpose of delegates is to
establish an infrastructure to support events
Defining Delegates
• A delegate is a reference type object that defines the signature and
return type of a method
• Delegate instances are used to refer to methods
• Any method that a delegate instance refers to must conform to the
signature of the delegate
• After a method has been assigned to a delegate, it is called when the
delegate is invoked
• Declaration syntax:
[modifiers] delegate
For example,
public delegate void TestDelegate(string message);
declares a function type: any method that returns void and accepts a
string parameter can be used where TestDelegate is indicated
Delegates and Handlers
• To use a delegate there must be a delegate method
handler
• This is a method that adheres to the delegate
signature
• The handler method implements some functionality
to be executed when the delegate referring to it is
invoked
• For a delegate method to be invoked it must be
assigned to a delegate object variable
• A delegate method handler is invoked by making a
method call on the delegate itself
Example
1. public delegate decimal Calculation(decimal val1, decimal val2);
2. public Calculation MyCalc;
3. public decimal Add(decimal add1, decimal add2)
{
return add1 + add2;
}
4. MyCalc = Add;
5. decimal result = MyCalc(5.35, 9.71); //result = 15.06
Events
• An event is a delegate with special features
• Events offer protections that delegates don’t
have
• Events are commonly used in GUIs
• Because all events are based on delegates the
type must be a delegate type
[modifiers] event
Events
• Programs that want to be notified when an event
occurs register their interest with the event provider
• The methods to implement an event must conform
to the signature and return type of the event’s
delegate type
• When events are invoked (fired), they are fired from
within the class that defines them
We’ll return to events in the Building Desktop
Applications with WPF module
Some advanced topics
C# is a rich language, with a great deal of
flexibility, so we won’t get to cover (or
use) all its features in this unit
However, it is possible you will encounter
or make use of some of the following
Lambda expressions
• Lambda expressions are a mechanism for defining
anonymous functions with a small amount of code
• They can, and often are, used in conjunction with
delegates. For example,
delegate int BinaryOp(int a, int b);
// then, later:
BinaryOp op = x, y => x + y;
//later still:
Console.WriteLine( op(1, 2) ); //prints 3
• The form of a lambda expression is:
parameter-list-without-types => expression
where expression is the result of the function
See https://msdn.microsoft.com/en-au/library/bb397687.aspx
https://msdn.microsoft.com/en-au/library/bb397687.aspx
Custom Type Conversions
• A conversion definition can be either implicit or explicit.
One of the types being converted must be the same type
as the enclosing class or struct
• The format for a conversion operator is:
public static
{
//conversion code
}
or implicit (conversion can safely be done so no special
action needed by the programmer)
Overloading Operators
• C# allows operator overloading, allowing you
to use operators such as +, * and == with your
own custom objects
• Mathematical and logical operators can be
overloaded
• Not all operators can be overloaded, refer to
the MSDN documentation for a complete list
Extension Methods
• C# allows you to attach methods to object
types, called extension methods
• Extension methods allow you to add methods
to classes that are sealed
• Extension methods are identifiable by the fact
that they are static and use the keyword this
as the first parameter
End of part 2 summary slides
Module 5
Introduction to software testing and
guide to use case-based testing
KIT206 Software Design & Development
KIT506 Software Application Design & Implementation
The general aim of testing is to…
1. …find the greatest number of faults…
2. …with a manageable amount of effort…
3. …over a realistic time span
If we assume that some faults exist, we want to
increase our chances of finding them without
expending too much effort in the search
Testing happens at every stage of SDLC
• Various testing activities occur at each stage of
the SDLC, even the design stages before any
software actually exists
• Module 8 will examine the full variety of
testing approaches in more detail, but before
then you will begin using one particular form
of systems level test: use case-based testing
• This form of testing is intended to identify
discrepancies between the software’s
functionality and what was specified in the
requirements document
Black box versus white box testing
Testing can take two broad forms:
• Black box testing treats the system as a sealed unit
– We can only interact with it using its interface
– Tests are planned based only on available interactions and
expected responses
• White box testing uses knowledge of the implementation
of a system
– Tests are designed to exercise all the (internal) execution paths
of a system, especially those likely to fail
– We may still interact with the system via its normal interface,
but make choices knowing what internal parts of the software
will be executed
Use case-based tests can use either approach, although
black box tests are more common since this form of testing
exercises the system through its interface (so often it can
simply be treated as a black box)
Creating a Test Plan
from Use Cases
Use case-based testing
• One approach to generating integration (systems
level) tests is to derive them from use cases
• The action–software reaction table from the
structured scenarios developed earlier in the
development process becomes the steps a test
user takes to test one aspect of the software
• Although structured scenarios are relatively high-
level, focusing on system behaviour rather than
implementation, the tests derived from them
may either black box or white box (using special
knowledge of the way the system has been
implemented)
• A Testing Report is a collection of such test cases
Use case test template
Description
Type and
Use Case
Criteria
Method
WARNING: one test is NOT sufficient. Think about whether you are
using white box or black box testing. If you are using black box
testing, one test that works is not enough to prove it will always
work. You should test each use cases with multiple sets of data.
Outcome
This template is available on MyLO
Repeat the table for every requirement that you have classified
as SW, SWC or P in the RTM, but not for each SWC # or P #
Repeat these rows for
each method of
testing the
requirement (that is,
for each alternative
series of steps a user
can take to test it)
Process for creating a testing report
• Make sure your RTM is correct and up-to-date
• For each requirement that you have classified as type SW,
SWC or P (a performance constraint) complete the
template
– If a requirement is classed as SWC # or P#, where # represents
an entry number of an SW requirement then rather than testing
that SWC/P separately, test it as part of the SW test: put the text
from the SWC or P requirement under criteria in the template
• Test the requirement to ensure that it meets all the criteria
– These criteria should be in the requirements document
– If they are not:
• you have to develop them now (in conjunction with client)
• the steps for a requirement classed as SW will be in a scenario (if
developed during the design phase) and you can use this to formulate
criteria
• there maybe some valuable criteria in the release schedule (not
covered in this unit)
• other documents produced during the design phase may give you
additional criteria
5.1 Researcher List
Upon application start up, the user shall be
presented with an interactive list of researchers…
This list should display names in the format
‘Family Name, Given Name (Title)’, …
The user shall be able to filter the Research List
view based on a researcher’s employment level or
student status. …
This would allow administrative staff to look at
performance of researchers within particular
employment bands more easily.
W
H
A
T
W
H
Y
H
O
W
V
E
R
IF
Y
A use case from the RAP
Test Report sample test
Description Upon application start up, the user shall be presented with an interactive list of researchers
(consisting of both staff and research students), known hereafter as the Researcher List view.
Type and Use Case SW UC8_User_views_ResearcherList
Criteria The application will provide a researcher information view (list and detail) that includes a list of
researchers’ names, formatted as ‘Family Name, Given Name (Title)’. The list will be visually
compact. This list may be filtered to show staff within a particular employment band (A–E) or
students only. The list may also be filtered based on partial, case-insensitive name matches.
Method Black box test:
1. Open the RAP application
2. The list of researcher names should immediately be visible
3. Names should appear as Family Name, Given Name (Title)
4. Select ‘B, Lecturer’ from the ‘Filter by Level’ drop-down list
5. The list of names should change
6. Select each entry in filtered list (UC16_User_views_ResearcherDetails) and confirm they
are level ‘B, Lecturer’
Outcome Pass
Method Black box test:
1. Ensure ‘Filter by Level’ is set to ‘All’.
2. Enter text ‘E’ into ‘Filter by Name’ field and press Enter.
3. The list of names should change; each entry should contain at least one ‘e’.
Outcome Fail – the list remains unchanged after step 2
Additional methods of testing this use case are possible. For instance, can the
original list of all researchers be successfully restored after it has been filtered?
The type of test (black box or white box)
is indicated as part of the method
No additional details for a test that passes
Must include details when it fails
These could be
dot-points for
each SWC
An example from another system
The user shall be able to save accounts data.
An option shall be available in the file menu
where the user will be able to choose to save
the data into an XML or Excel format file.
This feature allows accounts data to be entered
when available, and also allows the data to be
imported into Excel for further processing or
exported for display on web pages using XML.
WHAT
V
E
R
IF
Y
W
H
Y
H
O
W
A use case-based test for this requirement involves
a number of steps, shown on the next page
Test Report sample test
Description The user shall be able to save accounts data
Type and Use Case SW, UC20_User_saves_AccountsData
Criteria (taken from release schedule) An option shall be available in the main menu under the
file menu. Selecting this option shall open a standard file dialog, where the user will be
able to save the data into an XML file. An XML Schema will need to be developed and
the saved file must conform to this schema, allowing the file to be loaded onto a
webpage and also reloaded back into the software.
Method Black box test:
Step 1: Choose file menu
Step 2: Choose Save
Step 3: View File Dialog (only format available is XML)
Step 4: Choose Save
Step 5: Go to hard drive and check file is there
Step 6: Open the file using Dreamweaver to visually ensure the XML meets the schema
format
Step 7: Re-open the file using the software via the Open command in file menu and
visually check that all the data is still there.
Outcome Fail – The software could not be open the file as this functionality has not been
completed. The test passed all other steps.
You should have more methods and outcomes for this test. For example, in this
imaginary system we could try saving to a different file format.
The type of test (black box or white box)
is indicated as part of the method
Creating ‘good’ use case tests
The method section(s) of the report is the most important part:
• Use Black box or White box testing
• You should have multiple tests (methods) for each
requirement
• In most cases one method is not enough to pass
– You need to think of all the possible execution paths and test them all
– You need to think of the different types of input data and test them all
• If a test involves user interfaces you should also critique the
usability and appearance of those interfaces
– You can fail a test if you think the interface is unacceptable, even if it
completes the functionality
Module 6
Communicating with Data Sources
Summary plus details of connecting to
MySQL from C#
KIT206 Software Design & Development
KIT506 Software Application Design & Implementation
Index
Accessing Data with LINQ
Managing Data with ADO.NET
Reading data from a MySQL database
This all seems like too much effort just to
connect to a database
Accessing Data with LINQ
A summary of LINQ
LINQ
LINQ = Language Integrated Query
LINQ is a way to address the data access needs of
developers by enabling queries to be written directly in
the programming language
There has always been a problem bridging the semantic
gap between different types of data, whether multi-
value, object, relational or XML, a problem called
impedance mismatch
LINQ provides a similar mechanism to access all types
of data
https://en.wikipedia.org/wiki/Object-relational_impedance_mismatch
LINQ to Objects
Rather than using a loop to iterate through a
collection of objects and inspecting and
manipulating each one, LINQ provides a way to
tell the compiler what you want to do and then
have the compiler to work out how best to do it
It can thus replace the foreach loop you are
already familiar with in many situations
LINQ Syntax
LINQ syntax is SQL-like; it has common SQL
keywords like from, where, select, and variations
like groupby, order … into, etc.
Using the syntax though is slightly different to
how you would use it in SQL, for example the
from line goes first while the select line
generally goes last
var ‘implicit type’
C# allows variables declared at the method scope to
have the implicit type var
For example,
var i = 10;
The actual type of a variable declared with var is
determined by the compiler. Its use allows:
– Long type names (such as the interface name
IEnumerable
evaluate) to be shortened to just var; and
– To assign the result of LINQ expressions that do not
produce a named type (as C# allows ‘anonymous’
objects without a named class)
In fact, var is required in the second case
See the MSDN documentation for more
https://msdn.microsoft.com/en-us/library/bb383973.aspx
Example
List
{
new Employee {Name = “Marcus”, Gender = Gender.M },
new Employee {Name = “Nancy”, Gender = Gender.F },
new Employee {Name = “Chris”, Gender = Gender.M }
};
//var replaces the much longer IEnumerable
var maleStaff = from staffMbr in staff
where staffMbr.Gender == Gender.M
orderby staffMbr.Name
select staffMbr;
foreach (var mbr in maleStaff)
{
Console.WriteLine(mbr.Name);
}
Where to find more information
The MSDN pages on using LINQ in C# are the
best resource, covering all the keywords that
may appear in LINQ queries and showing
numerous examples
http://msdn.microsoft.com/en-us/library/bb397933.aspx
https://msdn.microsoft.com/en-us/library/bb397933.aspx
LINQ to SQL
One of the most useful applications of LINQ is to
write database queries within the programming
language rather than constructing strings
holding SQL
Unfortunately, without third-party libraries, this
only works with Microsoft’s SQL Server
(The good news is that once you’ve learnt the LINQ
syntax in one setting it won’t take you long to learn
how to use it when confronted with SQL Server)
Managing Data with ADO.NET
ADO.NET
• Historically, ActiveX Data Objects (ADO) was
Microsoft’s middleware layer for bridging the gap
between application data/objects and databases
• ADO.NET evolved from ADO and has become a
substantially different technology (the A from
ActiveX is largely legacy)
• ADO.NET is one of the main methods for
connecting to a database with C#
• It offers a higher level of abstraction and a more
OO approach to working with data
• It supports both a connected (transactional) and
disconnected (in-memory) approach
High Level ADO.NET architecture
Application
Data Reader DataSet
DataAdapter
Command
Connection
DataStore
Modes
Connected mode
• You must write code that explicitly opens and
closes a connection object
• This uses the operations Data Reader and
Command
Disconnected mode
• You work with the data in memory while you don’t
have an open connection
• This uses the operations Data Set and Data Adapter
Data Providers
A provider is a set of physical ADO.NET objects
that work for a specific data source
Some example data sources are:
– SQL Server
– Oracle
– ODBC
– OleDb (Access, Excel are examples)
– PostGresSQL
– MySQL
Reading from a MySQL
database
Refer to the accompanying
SqlCommandDemo.cs file for the
examples that follow
Getting set up (some specifics)
More complete details (and links to the appropriate driver) are
available in the accompanying HTML document, but here is a
summary:
1. For working on your own machine install the MySQL
Connector/Net drivers
2. To make them available to your C# project in Visual Studio,
go to Project | Add Reference…, select Extensions on the
left, then select MySql.Data in the list
Hover the mouse cursor over the three options and select the one that
has 4.5 in its path, because that will match the version of the .NET
platform you are using
The case study database this semester is called ‘kit206’
(username and password the same), and is located at:
alacritas.cis.utas.edu.au
Making Connections
• Before you can do anything with a database
your code must make a connection; this
establishes a session with a database
• An SQLConnection object must be instantiated
and opened to establish a database session
• Typically a database name, database location,
a user id and password are required to
establish a connection
Example of MySQL connection
//Normally these would be stored in a configuration file
private const string db = “kit206”;
private const string user = “kit206”;
private const string pass = “kit206”;
private const string server = “alacritas.cis.utas.edu.au”;
private MySqlConnection conn;
public SqlCommandDemo()
{
string connectionString = String.Format(
“Database={0};Data Source={1};User Id={2};Password={3}”,
db, server, user, pass);
//Create the connection object (does not actually make the connection yet)
conn = new MySqlConnection(connectionString);
}
// Calls methods that demonstrate SqlCommand capabilities for reading data
static void Main()
{
SqlCommandDemo demo = new SqlCommandDemo();
…
Making Connections
• The MySqlConnection uses a connection string
• This string is unique to the specific provider
• For this connection to work you need to be
using MySql.Data.MySqlClient;
• You also need to have the MySql.Data.dll in
the path or in Visual Studio you need to have
added it as a reference (see earlier advice)
Viewing data
• Use the SqlDataReader to view the data from
the Database
• A SqlDataReader may not be written or
modified and is an efficient means of
obtaining data
• For MySql use a MySqlDataReader
Example MySqlCommand
MySqlDataReader rdr = null;
try
{
// Open the connection
conn.Open();
// 1. Instantiate a new command with a query and connection
MySqlCommand cmd = new MySqlCommand(“select given_name, family_name from staff”, conn);
// 2. Call Execute reader to get query results
rdr = cmd.ExecuteReader();
// print the CategoryName of each record
while (rdr.Read())
{
//This illustrates how the raw data can be obtained using an indexer [] or
// a particular data type can be obtained using a GetTYPENAME() method
Console.WriteLine(“{0} {1}”, rdr[0], rdr.GetString(1));
}
} …
Disconnected Data
• Disconnected means that a connection is
made, the data is read into a DataSet and the
session is closed
• A DataSet is an in-memory database
Example Disconnected mode
var staffDataSet = new DataSet();
var staffAdapter = new MySqlDataAdapter(“select * from staff”, conn);
staffAdapter.Fill(staffDataSet, “staff”);
foreach (DataRow row in staffDataSet.Tables[“staff”].Rows)
{
//Again illustrating that indexer (based on column name) gives access to whatever data
//type was obtained from a given column, but can call ToString() on an entry if needed
Console.WriteLine(“Name: {0} {1}”, row[“given_name”], row[“family_name”].ToString());
}
LINQ to DataSet
• As you will have found out by trying to
understand the examples, a DataSet is not
easy to query
• LINQ to DataSet helps with this
• Use AsEnumerable() on the DataTable to
produce an Enumeration that is easy to
navigate
Manipulating database contents
Due to time constraints this topic is not covered
in this unit, but you can ask the unit coordinator
if you are interested
As a brief summary, manipulating MySQL
database contents involves the construction of a
standard SQL data manipulation command
string in a MySqlCommand object, the
application of any query parameters, and then
calling its ExecuteNonQuery() method
Why all this trouble?
Connecting from a C# application to a
MySQL database is a lot of work, so
what are the alternatives?
Options
Just within the Microsoft ecology of software development there is a wide
variety of technologies for communicating with databases. Here are some of
the alternatives you may encounter in the future
IMPLEMENT OR DITCH THIS
Database With Db structure Allows
Microsoft Entity
Framework
can be
modified
Object to relational database mapping; Entity
Framework handles loading of objects,
transactions, and persistence of changes
Non-MS EF + suitable
3rd-party
LINQ library
can be
modified
As above
Microsoft fixed LINQ can map database tables to ‘entities’;
although these won’t be the application’s own
objects, the transfer of data is made much easier
Non-MS 3rd-party
LINQ library
fixed As above
Non-MS fixed Individual queries use SqlCommand object
DataSet object can load parts of database and
can be queried with LINQ
Module 7
Building Desktop Interfaces with
Windows Presentation Foundation
(summary slides & guide to approaches
suitable for the assignment)
KIT206 Software Design & Development
KIT506 Software Application Design & Implementation
Suggested workflow
These slidesChapter 26, C# 3.0 Unleashed,
Mayo (2008)
MSDN sections on
topics of interest
Practice
Fast index
WPF and XAML
XAML for GUI design
Event handling
Data binding, data templates & styles
WPF and XAML
• In WPF, screens are built with a dialect of XML
called Extensible Application Markup
Language (XAML, pronounced zammil)
• XAML’s XML elements and nested structure
define the interface, which components it has
and how they are positioned and resized
• XAML can also be used to link controls to the
data they will display
• The XAML you edit directly, or construct via
the Visual Studio GUI builder, gets compiled
into code (that you never see)
.xaml and .xaml.cs
ClassName.xaml
• The XML that defines the interface, event
handlers and any resources
ClassName.xaml.cs
• The ‘code-behind’
• The C# code that implements the rest of
the class partially defined by the XAML
Each Window or UserControl in your project consists of two files
Uses of XAML
GUI Layout, including user controls
XAML used to
define GUI
appearance and to
connect event
handlers only
Data templates and styles
XAML used to
define customised
views and layouts
for different data
types
Data binding
XAML used to
connect GUI
elements data
sources
XAML is extremely versatile and so may be used at a number of levels of complexity.
The most basic is merely to define the layout of controls in a window and which
events will be handled. The next step is to define styles and views for specific data
types, while the last is using XAML to connect controls to data sources without writing
any additional code.
The following slides deal with these in the order 1, 3, 2,
because it is easiest to discuss data templates after having
connected a GUI element to a data source (although that
is not a necessary step to use a data template)
XAML for layout
NAME ™* to learn XAML for layout
Try it out!
There are many aspects to using XAML effectively that are not
intuitive, and so are detailed in these slides, but for learning how
different controls behave and what events they support, the
best way to learn is to play in Visual Studio (and have MSDN on
standby to answer questions as they arise)
Before jumping in, note that in VS you’ll see
(a spanner) to indicate properties and
(a lightning bolt) to indicate events
Note that a control must be given a name (either by setting the
x:Name property in XAML or via the Properties window) in order
to refer to it in the code-behind
*not a real trademark
Controls and Layouts
• The core of WPF is made up of controls (that
the user interacts with) and layouts (that
define the position and size of the controls
they contain)
• Each control can contain up to one other
control (which may be a layout), while layouts
can contain any number of controls
• The nested structure of the XAML elements
matches the container/contained
relationships between controls
Layouts
• Layouts are responsible for positioning and
determining the ultimate size of the controls
they contain
• You will likely use Grid and StackPanel layouts
most frequently
Tip: During development it can be useful to set
ShowGridLines to “True” when using the Grid layout
• See the chapter from C# 3.0 Unleashed and
the MSDN docs (and play in VS) to see how
Grids can either contain a single cell or be
divided up into cells of different sizes
‘Docking’ layouts
Windows Forms, the precursor to WPF, provided a
DockPanel layout, in which controls could be ‘docked’
to one of the borders of the layout. This can be
especially useful in windows that can be resized (see
next slide). Although this layout still exists, the need for
it is reduced, because
– setting a control’s height (or width)
to automatic (i.e., not specified in
the XAML);
– clearing its VerticalAlignment and
HorizontalAlignment; and
– setting its margins appropriately
mean that it will fill the available
space and respect those margins,
as if it were docked margins set for
left, top and
bottom
no height or
vertical
alignment set,
so will expand
to fill vertical
space
Layout such as Grid
ListBox
or
similar
width is set, so does not
expand horizontally
‘Docking’ a control without a DockPanel
A fragment of XAML for ‘docking’ a ListBox inside a Grid
(that has no rows or columns defined):
Notice that it’s mostly by removing properties (many of
which are set by default) that the control is made to stick
to one side of its containing Grid layout
In the Layout section of the properties pane, selecting the
following buttons for Horizontal- and VerticalAlignment
makes a control expand in that dimension
HorizontalAlignment
VerticalAlignment
Towards designing uable applications
• Rule of thumb: If you can allow the user to
resize an application window (to see more, for
instance) then do so
(many operating system settings windows are
still very poor in this regard)
• Corollary: If you do allow the user to resize the
window, make sure that the controls resize or
reposition themselves appropriately
Event handling
using XAML or delegates
Connecting event handlers using XAML
Event handlers (i.e., the methods that will be called
when an event occurs) can be specified as part of
your application GUI’s XAML
• Set an EventName property’s value to the name
of the event handler (i.e., method), typically via
the Events window, which creates the associated
method and adds the property to the XAML
– e.g.,
• The method specified can only be in the
control/window specified by the XAML, not
another class or object
Events and delegates
More information about events (beyond the scope of this unit) at MSDN
• Event objects are a special kinds of collection, where the
element type is a delegate (i.e., the specification for the kind
of method that can handle the event)
• So you can add a method belonging to any object to that
collection (provided it has the correct return type and
parameter list)
e.g., given an object called myHandler that defines a method
public void HandleIt(object sender, RoutedEventArgs e)
and the Button defined previously, in the code-behind for the
window we could register the event handler with
btnOK.Click += myHandler.HandleIt;
• A drawback to this approach is that it is no longer obvious
from the XAML alone which event handlers have been
registered on a control
https://msdn.microsoft.com/en-us/library/8627sbea.aspx
Data binding & data templates
Data binding
Data binding
to object properties
via a control’s
DataContext
via a Data
Template
to collections
and the various
formatting options
Data binding allows you to specify where a GUI control (such as
a list box or label) will obtain the values it will display at runtime
The mechanism is quite flexible, but we consider just three
forms: binding to an object’s properties (which is used in both
one-off collections of GUI controls and reusable Data Templates)
and binding to a collection of items (to populate a ListBox)
1
2
3
Click a topic to jump to it
4
Binding properties via DataContext
Each GUI component has a DataContext
property that can be used to indicate the
data it should display
One way of using this is to specify
(in the XAML) the name of an object’s
property that the control should use to
obtain displayable data
Then, at runtime, set that control’s
DataContext to the object you wish to
display
Setting the DataContext of a layout
element implicitly sets the DataContext for
all the controls it contains
DataContext null
NAME Context aPerson
e.g., a Label
lblName.DataContext = aPerson;
Name: NAME : 20
DataContext aPerson
lblName
lblAge
Binding to individual properties
For a Label (or TextBlock) set its Content (or Text) to a
binding definition of the form:
{Binding Path=PropertyName}
For example,
Will display value of GivenName property, if present
Will display value of FamilyName property, if present
Will display value of Age property, if present
Some options for formatting the bound values are covered later
An example of binding to properties
public class Staff {
public string FamilyName { get; set; }
public string GivenName { get; set; }
}
Imagine the following class has been
defined elsewhere in the project:
Then at runtime in the code-behind for the window:
…
Staff s = new Staff{ FamilyName=”Jones”, GivenName=”Fred” };
SomeContainer.DataContext = s;
…
//then, later still, we change the DataContext to an object
//with none of the referenced property names
SomeContainer.DataContext = new Object();
Personal Details:
NAME
Personal Details:
Note the age label
remains blank
Data binding for collections
• The general-purpose control ItemsControl and its derivations (i.e., child
classes) ComboBox, ListBox, TabControl and TreeView can be used to
present a collection of items on the GUI
• The collection of items can be set programmatically to some fixed
collection, or by binding the control’s ItemsSource property to a data
source
• There are a variety of options available, but we consider just one here,
binding to an in-memory collection
(note that the contents of the collection can still be drawn from a
database, but the binding is more indirect using this approach)
Programmatically
• In the code-behind, set the
control’s ItemsSource property
to a collection (e.g., List,
ObservableCollection, etc.)
• Drawback: Less obvious where
data is coming from when
reading the XAML
Binding ItemsSource to a
resource that is a collection
• Resource (that holds a List,
ObservableCollection, etc.) is
defined in XAML
• Drawback: obtaining a
reference to that resource in
the code-behind involves an
additional step, since it is
instantiated behind the scenes
Binding DataContext to a
DataSet
• Instead of setting ItemsSource,
set control’s DataContext to a
DataSet object (an in-memory
representation of a database)
• Drawback: Must load
substantial portion of the
database into memory
Not covered in this unitRecommended for this unit
Data binding to an object’s property
Given a ‘controller’ class (or a ‘view model’ in .NET’s model–view–view model
approach to MVC) that manages a collection of items, we can connect (bind)
its collection of items to a control such as a ListBox entirely in XAML.
Schematically this is like the following (note this is not a true class diagram):
The generic steps involved are:
1. modifying the XAML’s XML so that we can refer to our controller class;
2. defining a the controller class as resource (which means that an object of
the controller will be instantiated in the code generated from the XAML);
and
3. telling the ListBox to use that resource as its source of items.
The specific steps are described next
Db
Controller
-TheList : List
+GetList(): List
SomeWindow : Window
-lstItems : ListBox communicates withhas as a
resource
https://msdn.microsoft.com/en-us/library/bb613576(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/bb613576(v=vs.110).aspx
Preparing the controller
For your controller (or view model) class to be a resource that provides items it must define a
method that returns the collection of items (i.e., merely defining a property is not enough)
Tips:
• If the collection of items can change, make it an ObservableCollection rather than, say, a List.
Any time the collection is modified in the code, the display will automatically update
• If the collection will change due to filtering or similar operations, maintain two collections, the
master list that contains everything (and is always kept hidden) and the one that contains the
current items to be displayed (which should be an ObservableCollection)
namespace SomeProject
{
public class Item { public override ToString() { return “This is just an example item type”; } }
public class Controller
{
private List
private ObservableCollection
//…code to create the collections and copy values from masterList to viewableList…
public ObservableCollection
{
return viewableList;
}
}
}
Controller
-masterList : List
-viewableList : ObservableCollection
+GetList(): ObservableCollection
https://msdn.microsoft.com/en-us/library/bb613576(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/bb613576(v=vs.110).aspx
Binding ItemsSource to a collection
Once the controller/view model is ready, the procedure for binding it to the
control is as follows:
1. Add the project’s namespace as an XML namespace in the XAML
2. Inside either a Window.Resources element (or App.xaml’s App.Resources
element, to make globally accessible)…
1. Declare the controller (a new object will be created when the XAML is parsed)
2. Add an ObjectDataProvider that refers to that controller object and its method
that returns the collection it manages
3. Bind the ItemsSource property of the ListBox (or ComboBox, etc.) to that
ObjectDataProvider
…
https://msdn.microsoft.com/en-us/library/bb613576(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/bb613576(v=vs.110).aspx
ObjectDataProvider alternatives
There are two main ways to define an ObjectDataProvider:
1. via the two-stage process shown on the previous slide, which
produces (slightly) longer XAML but makes sharing the controller
simpler in the code (and is more likely inside App.Resources); or
2. by specifying the type of the controller class (and letting the
ObjectDataProvider create and manage the instance itself), which
makes the XAML simpler but access to the controller object more
difficult (and is thus more likely inside Window.Resources)
https://msdn.microsoft.com/en-us/library/bb613576(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/bb613576(v=vs.110).aspx
In the code-behind
If the Window or UserControl needs access to the
controller object (which is fairly common) then use the
FindResource method to obtain a reference
If the controller was declared independently in XAML:
Controller c = (Controller) FindResource(“controller”); //if declared in Window
//or the following if declared as a resource in App.xaml
Controller c = (Controller) Application.Current.FindResource(“controller”);
If only the ObjectDataProvider was declared:
ObjectDataProvider listProvider = (ObjectDataProvider)FindResource(“MyList”);
Controller c = (Controller) listProvider.ObjectInstance;
Binding to a list of Enum values
It is relatively common to have a drop down list box that
shows the values of some enumerated type (provided the
internal enum names are suitable for human consumption)
This can be achieved either by writing code to place each
Enum value in a list and using it as the ItemsSource, or by data
binding in the XAML (since the Enum class already has a
method for returning an array of enum values, illustrated here
and in this online example)
Schematically this looks like:
System::Enum
+GetValues(Type t): Array
SomeWindow : Window
-cmbOpts : ComboBox uses
«enumeration»
Category
FullTime
Casual
FixedTerm
uses
https://msdn.microsoft.com/en-us/library/bb613576(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/bb613576(v=vs.110).aspx
Steps in binding to a list of Enum values
1. Add the .NET System namespace as an XML namespace
2. Add the project’s namespace as an XML namespace
3. Add an ObjectDataProvider to Window.Resources that uses the
Enum class’s GetValues() method to obtain the values of your
enumerated type
4. Bind the ItemsSource property of the ListBox or ComboBox to that
ObjectDataProvider
(in this case the enum is named Category)
…
https://msdn.microsoft.com/en-us/library/bb613576(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/bb613576(v=vs.110).aspx
Data templates
By default, a ListBox or other ItemsControl uses the
ToString() method of its elements to generate a
displayable string
Data templates allow more complex, ad hoc (i.e.,
without the overhead of defining a new user control)
structures to be used to present information
(There may be more places in the assignment to use
these than you might at first think)
Data templates: general steps
1. Define a DataTemplate as a resource in the Window or
UserControl
1. The contents of the DataTemplate are layout and control elements
2. Each control element, such as a Label or the more compact TextBlock, has its
Content (or Text, for a TextBlock) property set to
{Binding Path=ObjectPropertyName}
3. In the root element of the DataTemplate either:
a) Set its x:Key attribute so that it can be referred to elsewhere (later you must
manually indicate where it should be used) or
b) Set its DataType property to the type of data it should be used for (anywhere within
the Window or UserControl that that type of data is displayed the template will be
applied), as in
Note that this option requires that the namespace for your classes be imported, as
done when data binding
2. If you went for option 1.3.a, on the ListBox or equivalent set its
ItemTemplate property to the DataTamplate; e.g., if the
DataTemplate’s key was MyTemplate:
Basic Example: display an item in a Grid
…
Elsewhere…
public class Staff {
public string FamilyName { get; set; }
public string GivenName { get; set; }
}
This merely specifies the
structure of the grid: 1 row,
2 columns
The binding path indicates
the property of the object to
read to set the Content
property of the label
Basic Example: display an item in a Grid
Later in the XAML file
Assumes some collection
of these Staff objects also
defined as a resource
The effect at runtime
Bloggs Fred
NAME
NAME
Example 2: using TextBlocks & DataType
…
This means that whenever a Staff
object is added to a ListBox or similar in
this Window, the template will be used
TextBlocks are a good
alternative if you want the
output to be compact
(they’re also especially good
in WindowsPhone apps,
because they use fewer
resources)
Example 2: using TextBlocks & DataType
Later in the XAML file
Assumes some collection
of these Staff objects also
defined as a resource, but
no need to define
ItemTemplate
Bloggs, NAME , NAME , NAME effect at runtime
Using a DataGrid for tabular data
The DataGrid control supports the flexible display of tabular data
with column headings
Each row represents the details of one object in a collection
The DataGrid control combines collection-level binding via its
ItemsSource property and object property-level binding to
specify which object property each column should display
The following example is suitable for a non-editable table:
Family Name Given Name
Bloggs Fred
NAME
NAME
String formatting for bound values
Sometimes you will need a property value displayed by a
TextBlock or Label to be formatted differently from its default
For example, real-valued numbers may represent currency
amounts ($5.00) or percentages (31%), while dates often need to
be presented in some user-preferred format (Sun 6 Sep)
This can be achieved by setting either the StringFormat or
ContentStringFormat properties, depending on the kind of
control:
Note that a TextBlock’s StringFormat is part of the Text property,
while a Label’s ContentStringFormat is a standalone property
…
…
String formatting examples
…
…
See the list of formatting strings for different types at
https://msdn.microsoft.com/en-us/library/26etazsy(v=vs.110).aspx
Given this declaration
public class Datum {
public double Real { get; set; }
public DateTime DOB { get; set; }
}
And setting the labels’ DataContext to:
new Datum {
Real = 3.1415, DOB = DateTime.Today
};
$3.14
3.1
9/6/2015
Sun 09 Sep
A short date, by
default in US format
A custom date format
A currency, by default
in $ format
https://msdn.microsoft.com/en-us/library/26etazsy(v=vs.110).aspx
Styles
• Styles allow formatting to be specified in one
place and then reused across multiple controls,
which is especially useful if complex formatting is
desired in different places in the GUI
• Styles are defined in the Resources section and
given a Key to refer to them elsewhere
• Each Style specifies the Control type it is for
• The Style’s contents are a series of elements
corresponding to setters for property values
(behind the scenes the style is applied by
executing these commands)
Applying a style
Adapting the Grid and Label example from before:
…
…
…
The effect at runtime (ugly,
but merely a demonstration)
Bloggs Fred
NAME
NAME
Additional examples
A complete working example of most of these
techniques is available as the solution to the
Week 10 and 11 tutorials
Module 8
Testing Across the SDLC
KIT206 Software Design & Development
KIT506 Software Application Design & Implementation
Suggested workflow
Chapter 11 of Object-Oriented
Software Engineering Using
UML, Patterns, and Java,
Bruegge & Dutoit (2012)
Skim read these
slides first
Remainder of these
slides as a summary
Celebrate completing
all the online modules
Reading: Software Testing
Excepts from Chapter 11 (~30 pages) in
Object-Oriented Software Engineering Using UML, Patterns, and Java,
3rd ed, by Bruegge & Dutoit, 2009
Location: PDF on MyLO
Summary: Testing occurs at every stage of the SDLC and takes a variety
of forms depending on the stage and software artefact being tested
(document, code, etc.). OO software has additional needs when being
tested because, although object-orientation can make software more
flexible and maintainable, it also adds complexity to its behaviour.
Although you will not have the opportunity to put all the different
forms of testing they describe into practice, it is worth being aware of
the different kinds of testing that developers perform.
Note that Bruegge & Dutoit refer to a Requirements Analysis
Document as RAD throughout this chapter. For our purposes
this is the same as the combination of Requirements
Document and Requirements Trace Matrix.
Testing happens at every stage of SDLC
• Testing is not a final stage in the SDLC, but an
ongoing process that is woven throughout the
development process
• Testing is not confined to the execution of
software (designs can also be tested)
• It is easy to develop an incorrect understanding
of the role of testing because:
– the way technical topics are taught in isolation, testing
is not shown to be integral to the process (this is a
failing of us, your teachers); and
– the way students typically approach technical
problems is the build-and-fix approach to software
development; testing is ad hoc and generally
insufficient to guarantee software robustness
The purpose of testing is to find faults
• Testing is not
– a separate phase of the lifecycle;
– just debugging of programs; or
– about proving the absence of faults (this is
impossible for even moderately-sized software)
• Testing is often described as:
“Finding faults in a planned way”
The general aim of testing
1. Find the greatest number of faults…
2. …with a manageable amount of effort…
3. …over a realistic time span
If we assume that some faults exist, we want to
increase our chances of finding them without
expending too much effort in the search
Additional considerations in OO
For OO analysis and design the general aim needs to be broadened. Keep in
mind these possible (design) errors:
• improper allocation of a class to a subsystem
• improper allocation of a class to a task
• extraneous attributes
• messaging problems, such as the wrong subclass object assigned to
variable of a superclass type
– For example: Person p referring to an Employee object instead of a
Student (this error may be difficulty to identify at runtime and to correct)
• Some types of faults become less plausible
– particularly at unit level (OO has done its job and managed complexity)
• Some types of faults become more plausible
– particularly integration (OO has increased the complexity of interactions
between subsystems)
• Some new types of faults appear
– due to inheritance (and multiple inheritance), also because OO can increase
complexity of possible interactions
Fast index to rest of these slides
Testing activities
Approaches to testing software by running it and
by review
Unit testing
Integration testing
Testing activities
Functional test
Structure test
UserClientDeveloper
Integration test
Unit test
Test planning
User interface
design
Usability test
A schematic overview of testing activities
Management plan
From SPMP
Object design
From OOD
Integration strategy
From TP
System
decomposition
From SDD
Functional
requirements
From Reqs
From Reqs
Non-functional
requirements
From Reqs
User manual
Field test
Project
agreement
Daily operation
Installation test
Acceptance test
Performance test
SPMP = Software Project Management Plan
OOD = OO design document
TP = Testing Plan
SDD = Software design document
Reqs = Requirements/RTM
D
O
N
O
T
A
T
T
E
M
P
T
T
O
M
E
M
O
R
IS
E
T
H
IS
S
T
R
U
C
T
U
R
E
Black box versus white box testing
Testing can take two broad forms:
• Black box testing treats the system as a sealed unit
– We can only interact with it using its interface
– Tests are planned based only on available interactions and
expected responses
• White box testing uses knowledge of the implementation
of a system
– Tests are designed to exercise all the (internal) execution paths
of a system, especially those likely to fail
– We may still interact with the system via its normal interface,
but make choices knowing what internal parts of the software
will be executed
Some testing activities can be performed using either
approach, while others are necessarily only black box or
only white box
Where does ad hoc testing fit in?
Most of the testing done by university students is
ad hoc: unstructured, unplanned, minimal
(the size of the software projects and the rewards
on offer [marks] do not encourage anything more
robust)
Functional test
Structure test
UserClientDeveloper
Integration test
Unit test
Test planning
User interface
design
Usability test
Management plan
From SPMP
Object design
From OOD
Integration strategy
From TP
System
decomposition
From SDD
Functional
requirements
From Reqs
From Reqs
Non-functional
requirements
From Reqs
User manual
Field test
Project
agreement
Daily operation
Installation test
Acceptance test
Performance test
This testing is rarely low-level enough
to qualify as a unit test (more later),
and is mostly at the functional level,
but can at times be similar to an
integration test (for instance, when
running a program before it’s
finished)
What testing activities we cover in this unit
Given time constraints, we discuss (and will
examine) a broad range of testing activities, but
will largely practise Functional Tests through use
case-derived test cases (see Module 5)
Given the nature of
the project, some
of these tests will
also be similar
acceptance tests
Functional test
Structure test
UserClientDeveloper
Integration test
Unit test
Test planning
User interface
design
Usability test
Management plan
From SPMP
Object design
From OOD
Integration strategy
From TP
System
decomposition
From SDD
Functional
requirements
From Reqs
From Reqs
Non-functional
requirements
From Reqs
User manual
Field test
Project
agreement
Daily operation
Installation test
Acceptance test
Performance test
Testing software with
software and by review
Testing concepts
Component
• Part of the system isolated for testing (object(s), subsystem)
Fault (bug, defect)
• Mistake that may cause abnormal behaviour
Erroneous state
• Caused by faults during execution
Failure
• Deviation between expected (specified) and actual behaviour
• Triggered by erroneous states
Test case
• Specification of a given test
• Set of inputs and expected results
Test Driver
• Simulates the part of the system that calls the component under test
Test Stub
• Simulates components called by the component under test
A conceptual overview of test concepts
Test suite
Test case
Failure
Component
Error Fault
Correction
Test stub
Test driver
*
*
* * * *
*
*
*
*
1..n
exercises is revised by
repairsfinds
is caused by is caused by
Code Review
Software testing is not only performed by running it
(under test conditions)
Code reviews give other developers the opportunity
to identify faults in a software artefact’s design
The main forms this takes are:
• Code Walkthrough
– developer presents API and documentation to review
team
• Code Inspection
– performed by inspection team
– more formal
Unit Testing
Low-level testing of separate (small) parts of
a system
Even when not done formally (i.e., not using
a testing framework) the principles of unit
testing can inform your approach to ad hoc
testing and debugging
Jump to integration testing
Low-level testing of ‘units’
• Unit testing tests individual functions and
methods of a system
• Testing individual components in isolation allows
the testing to be
– simpler
– making it easier to spot some faults
– and allows automated tests to be run in parallel
• Many techniques and strategies exist; an
overview of each is presented over the following
slides
– Equivalence testing
– Boundary testing
– Path testing
– State-based testing
– Polymorphism testing
Equivalence Testing
Aims to minimise number of test cases
Partitions inputs into equivalence classes
• Only need to test single member of the class
Criteria:
• Coverage (all possible inputs represented)
• Disjointedness (no input in multiple classes)
• Representation (ever member of a class should
detect the same erroneous state)
Boundary Testing
Special case of equivalence testing
Selects elements from “edges” of classes
• e.g., null values, empty strings, “off-by-one”
values
Path Testing
White-box; tries to exercise every path through the
code
Requires a flow graph of the code
• Minimum number of tests required = #edges – #nodes + 2
• (number of independent paths through graph)
In general, can’t detect omissions from the code
State-based Testing
Tests expected transitions through a state diagram
Derive stimuli (inputs) from diagram (similar to
equivalence class testing) to test each transition
Polymorphism Testing
The use of polymorphism simplifies the written code, but
potentially introduces many more paths through the code
Every possible binding (introduced by inheritance
polymorphism) must be tested
• Can easily result in an explosion of test cases
(Unit) Testing Frameworks
• Constructing unit tests manually is problematic,
so should use a testing framework
• There exist a variety of testing frameworks
depending on your development language
• For instance,
– JUnit is a widely used framework for Java (but several
others exist, so there are many alternatives for the
one language)
– The .NET platform also supports unit tests (one unit
test framework for many languages)
– Although there are significant differences between
them, there are also general similarities: learning
whichever you need is often just a matter of reading
the relevant documentation
Integration & system testing
Integration Testing
• Tests integration of components tested individually
during unit testing
• Use case-based testing, which you are performing
in the assignment, is a form of integration test
• Strategies (see reading for details):
– “Big-bang” (not recommended!)
– Bottom-up
– Top-down
– Sandwich (hybrid of previous two)
System Testing
Testing a system as a whole can take many forms,
including:
• Functional testing
– is black box; derived from use cases
• Performance testing, which can include
– stress-testing
– volume testing
– security (penetration) testing
• Pilot testing
• Acceptance testing
• Installation testing
The reading expands on these
Other issues to consider
• Regression tests
– when a change is made, rerun tests to ensure that
the change has not introduced errors or
incompatibilities elsewhere in the system
• Automation
– integrating unit tests into build files (a topic not
covered in this unit) can allow the process to be
done upon each significant change
• Documentation
– Tests also need to be documented
Tips: When short of time to do testing
After a component has been changed run the
tests that test the classes dependent on the
changed class first
Run the test cases that test the frequently
used cases first
Run the tests that test major risks first
Module 2
Suggested workflow
The big picture of object-oriented design
Our location in the process
Reading: Modelling and Objects
The Unified Modelling Language
UML
Reading: A first look at UML
Types of UML diagrams
UML Diagrams
Static (structural) diagrams
Dynamic (behavioural) diagrams
Reading: UML Tutorial
Module 2, part 2…
Module 2
Suggested workflow
Quick index
Approaches to modelling a system based on use cases
An important heuristic (rule of thumb)
Package Diagrams
Class Diagrams
Sequence Diagrams
Static/structural modelling with UML
Structural Analysis
Creating class diagrams
Entity Objects
Noun-phrases
“Entity” object identification
Common class modelling
Example from RAP
Boundary Objects/Classes
Identifying Boundary Objects
Control Objects/Classes
Example from RAP
Identifying Attributes
Identifying Attributes
Example from RAP
Identifying Operations: a RAP example
Class Relationships
Identifying Associations
Identifying Aggregations
Identifying Inheritance
Abstract/Concrete Classes
Aggregating classes into packages
Package
Why group classes into packages?
Package Diagrams
Coupling↓ + Cohesion↑
A process to assess packages
Example from RAP
Package Diagram
Refining static analysis
Dynamic modelling
Dynamic modelling
UML for dynamic aspects of a system
Use Cases
Use Case Diagram
Sequence Diagram
Events, not operations
Sequence Diagram
Creating sequence diagrams
An example (taken from a textbook)
Example (continued)
Another example
Start simple…
…then elaborate and add details
An example from the RAP
An example from the RAP
Final words
Module 5
The general aim of testing is to…
Testing happens at every stage of SDLC
Black box versus white box testing
Creating a Test Plan�from Use Cases
Use case-based testing
Use case test template
Process for creating a testing report
A use case from the RAP
Test Report sample test
An example from another system
Test Report sample test
Creating ‘good’ use case tests
Module 6
Index
Accessing Data with LINQ
LINQ
LINQ to Objects
LINQ Syntax
var ‘implicit type’
Example
Where to find more information
LINQ to SQL
Managing Data with ADO.NET
ADO.NET
High Level ADO.NET architecture
Modes
Data Providers
Reading from a MySQL database
Getting set up (some specifics)
Making Connections
Example of MySQL connection
Making Connections
Viewing data
Example MySqlCommand
Disconnected Data
Example Disconnected mode
LINQ to DataSet
Manipulating database contents
Why all this trouble?
Options