Software Construction & Design 1
The University of Sydney Page 1
Software Design and
Construction 1
SOFT2201 / COMP9201
Introduction to Software
Construction & Design
School of Computer Science
Dr. Martin McGrane
The University of Sydney Page 2
Copyright Warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been reproduced and communicated to
you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the
Act ).
The material in this communication may be subject
to copyright under the Act. Any further copying or
communication of this material by you may be the
subject of copyright protection under
the Act.
Do not remove this notice.
The University of Sydney Page 3
Agenda
– Workplace Health and Safety
– Course Arrangements and Information
– Software Engineering
– Software Modeling
– The Unified Process
The University of Sydney Page 4
WHS Induction
The University of Sydney Page 5
Emergency procedures (on campus)
– In the unlikely event of an emergency, we may need to evacuate the building.
– If we need to evacuate, we will ask you to take your belongings and follow
the green exit signs.
– We will move a safe distance from the building and maintain physical
distancing whilst waiting until the emergency is over.
– In some circumstances, we might be asked to remain inside the building for our
own safety. We call this a lockdown or shelter-in-place.
– Further information is available at www.sydney.edu.au/emergency
http://www.sydney.edu.au/emergency
The University of Sydney Page 6
Keeping our community safe
We can all help reduce the spread of COVID-19 through following good hygiene
practices:
– Wash hands regularly, for at least 20 seconds with soap and water, or use an
alcohol-based hand rub.
– Cover your mouth when coughing and sneezing with a tissue or a flexed
elbow.
– Maintain a distance of at least 1.5m between yourself and others, where
possible.
– Avoid large gatherings, where possible.
– Avoid close contact with anyone with cold or flu symptoms, e.g., fever, cough,
runny nose or shortness of breath.
The University of Sydney Page 7
Keeping our community safe
– All students and staff who have cold or flu symptoms should isolate themselves
from others.
– If you are unwell with any symptoms, please excuse yourself from this class
and get tested for COVID-19 as soon as possible. We will support you to
continue the work remotely.
– Make sure you read the information on special consideration in the unit
outline.
The University of Sydney Page 8
Keeping our community safe
– The University is following advice from the government and related public
health authorities.
– For the latest information, see the advice on the University website.
– In some classes, especially those involving use of shared equipment, please
follow additional advice from your coordinators.
– Please take care of each other and yourselves and if you need support reach
out to your unit coordinator or the health and wellbeing area of the Current
Students website.
https://sydney.edu.au/study/coronavirus-infection-university-of-sydney-advice.html
https://sydney.edu.au/students/health-wellbeing.html
The University of Sydney Page 9
Tips for students learning online
– For tips and guides on learning online and the tools you will use, refer to Learning
while off campus resources in Canvas.
https://canvas.sydney.edu.au/courses/4901/pages/learning-while-off-campus
The University of Sydney Page 10
Disability Services Office
sydney.edu.au/disability
02-8627-8422
Do you have a disability?
You may not think of yourself as having a ‘disability’ but the
definition under the Disability Discrimination Act (1992) is broad
and includes temporary or chronic medical conditions, physical or
sensory disabilities, psychological conditions and learning
disabilities.
The types of disabilities we see include:
Anxiety // Arthritis // Asthma // Autism // ADHD
Bipolar disorder // Broken bones // Cancer
Cerebral palsy // Chronic fatigue syndrome
Crohn’s disease // Cystic fibrosis // Depression Diabetes //
Dyslexia // Epilepsy // Hearing impairment // Learning disability //
Mobility impairment // Multiple sclerosis // Post-traumatic stress //
Schizophrenia // Vision impairment
and much more.
Students needing assistance must register with Disability Services.
It is advisable to do this as early as possible. Please contact us or
review our website to find out more
http://sydney.edu.au/study/academic-support/disability-support.html
The University of Sydney Page 11
Other support
– Learning support
– http://sydney.edu.au/study/academic-support/learning-support.html
– International students
– http://sydney.edu.au/study/academic-support/support-for-international-
students.html
– Aboriginal and Torres Strait Islanders
– http://sydney.edu.au/study/academic-support/aboriginal-and-torres-
strait-islander-support.html
– Student organisation (can represent you in academic appeals etc)
– http://srcusyd.net.au/ or http://www.supra.net.au/
http://sydney.edu.au/study/academic-support/learning-support.html
http://sydney.edu.au/study/academic-support/support-for-international-students.html
http://sydney.edu.au/study/academic-support/aboriginal-and-torres-strait-islander-support.html
The University of Sydney Page 12
Assistance
– There are a wide range of support services available for students
– Please make contact, and get help
– You are not required to tell anyone else about this
– If you are willing to inform the unit coordinator, they may be able to work
with other support to reduce the impact on this unit
– E.g. provide advice on which tasks are most significant
The University of Sydney Page 13
Special Consideration (University policy)
– If your performance on assessments is affected by illness or misadventure
– Follow proper bureaucratic procedures
– Have professional practitioner sign special USyd form
– Submit application for special consideration online, upload scans
– Note you have only a quite short deadline for applying
– http://sydney.edu.au/current_students/special_consideration/
– Also, notify coordinator by email as soon as anything begins to go wrong
– There is a similar process if you need special arrangements, e.g., for
religious observance, military service, representative sports
http://sydney.edu.au/current_students/special_consideration/
The University of Sydney Page 14
Academic Integrity (University policy)
– “The University of Sydney is unequivocally opposed to, and intolerant of,
plagiarism and academic dishonesty.”
– Academic dishonesty means seeking to obtain or obtaining academic advantage for oneself or for
others (including in the assessment or publication of work) by dishonest or unfair means.
– Plagiarism means presenting another person’s work as one’s own work by presenting, copying or
reproducing it without appropriate acknowledgement of the source.” [from site below]
– http://sydney.edu.au/elearning/student/EI/index.shtml
– Submitted work is compared against other work (from students, internet, etc)
– Turnitin for textual tasks (through eLearning), other systems for code
– Penalties for academic dishonesty or plagiarism can be severe
– Complete self-education AHEM1001 (required, canvas → assessment info)
http://sydney.edu.au/elearning/student/EI/index.shtml
The University of Sydney Page 15
Unit/Course Overview
The University of Sydney Page 16
SOFT2201/COMP9201 Lectures and Tutorials
– Lecture:
– Monday, 5pm to 7pm (AEST), Zoom (w1 to w13, public holiday excluded)
– Tutorial:
– SOFT2201: 2h tutorial, on Tuesdays and Wednesdays, Zoom (w2 to w13)
– COMP9201: 2h tutorial, on Thursday, Zoom (w2 to w13)
– Check your timetable
• Attend ONE (go to the tutorial you’re scheduled for)
– Hands-on practical exercises
• Tutors to supervise your learning and provide guidance
The University of Sydney Page 17
Tips for students joining online
– Please mute your microphone when not speaking.
– Try not to talk over someone else.
– When you have questions during live lectures:
– if questions are public and can be read in recording mode, feel free to type them
on zoom chat and I will read and answer them during the lecture
– if questions are private, please use the contact hour
– When you have questions during tutorials:
– feel free to ask questions to tutors during group discussion or Q&A session
The University of Sydney Page 18
SOFT2201/COMP9201 Staff
Course Coordinator:
– Dr. Ying Zhou (ying. .au)
Lecturer:
– Dr. Martin McGrane ( .au)
– Consultation: Monday, 4pm to 5pm (AEST), Zoom
Tutor allocation can be found via Staff and Contact Details on canvas
mailto:ying. .au
mailto: .au
https://canvas.sydney.edu.au/courses/25987/pages/staff-and-contact-details
The University of Sydney Page 19
SOFT2201/COMP9201 Resources
– Canvas (eLearning)
– Announcements (important)
– Modules: Copies of lecture slides, Tutorial instructions
– Assignments: Assignment instructions
– Recorded Lectures
• Lecture recordings (usually upload after 1~2 hours of the live lectures)
– Zoom: Live lectures, lecture question time, and tutorials
– Ed
• The best place to ask technical questions about the course.
• Discussing non-assessed exercises, such as from tutorials, is encouraged.
• Don’t post your assignment code and ask what’s wrong with it.
• You will get faster answers here from staff and peers than through email.
The University of Sydney Page 20
Prerequisites
– This course has the following prerequisites:
– INFO1113 OR INFO1103 OR INFO1105 OR INFO1905
– This means that we expect students who enroll in this course to be:
– Confident Java programmers
– Familiar with data structures
– Prohibitions
– INFO3220 OR COMP9201 (for SOFT2201 students)
– INFO3220 OR SOFT2201 (for COMP9201 students)
https://cusp.sydney.edu.au/students/view-unit-page/alpha/INFO1113
https://cusp.sydney.edu.au/students/view-unit-page/alpha/INFO1103
https://cusp.sydney.edu.au/students/view-unit-page/alpha/INFO1105
https://cusp.sydney.edu.au/students/view-unit-page/alpha/INFO1905
https://cusp.sydney.edu.au/students/view-unit-page/alpha/INFO3220
https://cusp.sydney.edu.au/students/view-unit-page/alpha/COMP9201
https://cusp.sydney.edu.au/students/view-unit-page/alpha/INFO3220
https://cusp.sydney.edu.au/students/view-unit-page/alpha/SOFT2201
The University of Sydney Page 21
Main Resources
• We recommend the following textbooks
Link to USYD Library Link to USYD Library
https://sydney.primo.exlibrisgroup.com/discovery/fulldisplay?docid=alma991031515434805106&context=L&vid=61USYD_INST:sydney&lang=en&search_scope=MyInst_and_CI&adaptor=Local%20Search%20Engine&tab=Everything&query=any,contains,design%20patterns%20ele
https://sydney.primo.exlibrisgroup.com/discovery/fulldisplay?docid=proquest37705939&context=PC&vid=61USYD_INST:sydney&lang=en&search_scope=MyInst_and_CI&adaptor=Primo%20Central&tab=Everything&query=any,contains,applying%20uml%20and%20patterns&offs
The University of Sydney Page 22
Additional Resources
• We recommend the following textbooks
Link to USYD Library Link to USYD Library
https://sydney.primo.exlibrisgroup.com/discovery/fulldisplay?docid=springer_s978-1-4842-1802-0_395506&context=PC&vid=61USYD_INST:sydney&lang=en&search_scope=MyInst_and_CI&adaptor=Primo%20Central&tab=Everything&query=any,contains,java%20design%20pa
https://sydney.primo.exlibrisgroup.com/discovery/fulldisplay?docid=alma991031514930405106&context=L&vid=61USYD_INST:sydney&lang=en&search_scope=MyInst_and_CI&adaptor=Local%20Search%20Engine&isFrbr=true&tab=Everything&query=any,contains,uml%20disti
The University of Sydney Page 23
Topics Overview
Week Contents Week
1 Introduction; Software Engineering, Software Modeling, The Unified Process
2 OO Theory I: Java Knowledge Revisited
3 UML & Software Modelling Case Studies
4 OO Theory II: Software Design Principles and Design Smells
5 Design Pattern: Factory Method & Builder Design Pattern: Strategy & State 6
7 Testing Code Review 9
10 Design Pattern: Adapter & Observer Design Pattern: Prototype & Memento 11
12 Design Pattern: Singleton, Decorator and Facade
13 Unit Review
The University of Sydney Page 24
Tutorial Work
– 2-hour tutorial work:
– Generally, 1hr 30 minutes tutorial content + 20 minutes Q&A session
– Check your schedule and allocation on the timetable
– Great opportunity for interactive and hands-on learning experience
– Respect your tutors and value their feedback
– Respect your classmates
– Tutors will supervise your learning, provide you guidance
– Not to debug your code, or solve the problems for you
The University of Sydney Page 25
Language and Tools
– Your coding will be in Java 11
– You will use IntelliJ for writing your code
– You will use JavaFX for designing your GUIs
– You will use supporting tools such as Gradle, Git, etc.
The University of Sydney Page 26
Assessment
What (Assessment)* When (due) How Value
Weekly Exercises Weekly Submission on Canvas 10%
Software Construction
Stage 1
Week 4 Individual Submission on
Canvas
5%
Software Construction
Stage 2
Week 8 Individual Submission on
Canvas
15%
Software Construction
Stage 3
Week 12 Individual Submission on
Canvas
20%
Exam Exam period Individual exam 50%
The University of Sydney Page 27
Weekly Exercises
– Weekly exercises can be found under each week module on Canvas.
– Exercises cover contents from recent tutorials and lectures
– Timeframe:
– Exercises and submission portals are released at 8am (AEST) Tuesday
– Exercises due and submission portals are closed at 23.59pm (AEST) Sunday
– You can do the exercise any time after it is open and before its due
– However, once it is closed, without SCON, you cannot re-take it if you miss it
– Total marks: 10%
The University of Sydney Page 28
Assignment
– Three individual assignments (40% marks):
1. Design a computer game using UML diagrams
– You are going to submit UML diagrams + recorded presentation (< 5 minutes)
2. Implement the computer game described in the UML using Java with JavaFX
– You are going to submit implementation code + report about the design principles/design
patterns in your implementation + recorded presentation (< 10 minutes)
3. Test, review and extend code
– You are going to submit implementation code + report about the design principles/design
patterns of the receiver code and your extensions + test cases + presentation recording (<
10 minutes)
The University of Sydney Page 29
Late Assignments
– Suppose you hand in your assignments after the deadline:
– If you have not been granted special consideration or arrangements
– A penalty of 5% of the available mark will be taken, per day late
• E.g., your work would have scored 60% and is 1 day late you get 50%
– Assignments after 10 calendar days late get 0
– Late penalty doesn’t apply to weekly exercises; you cannot re-take the exercise if
you miss it
– Warning: submission sites get very slow near deadlines
– Submit early; you can resubmit if there is time before the deadline
The University of Sydney Page 30
Online Final Exam
– 2hrs, will be organized by Exam Office during Exam period
– More details will be announced at the end of the semester (w13)
– Total marks: 50%
The University of Sydney Page 31
Passing this unit
– To pass this unit you must do all of these:
– Get a total mark of at least 50%
– Get at least 40% for your final exam mark
The University of Sydney Page 32
SOFT2201/COMP9201 Expectations
– Students attend scheduled classes, and devote an extra 10 hours per week
– Prepare and review lecture and tutorial materials
– Revise and integrate with ideas
– Carry on the required assessments
– Practice and self-assess
– Students are responsible learners
– Participate in classes, constructively
• Respect for one another (criticise ideas, but not people)
• Humility: none of us knows it all; each of us knows valuable things
– Check eLearning site very frequently
– Know the Uni/school policies
The University of Sydney Page 33
Q&A and Feedback
– A discussion forum is setup:
– Please use ED for technical questions so that everybody can benefit from
the questions and answers
– Talk to us:
– After lectures/tutorials
– During teaching staff consultation
– Feedback to you will take many forms:
– Verbally by your tutor
– As comments accompanying hand marking of your assignment work and
exercises work
The University of Sydney Page 34
Advice
– Metacognition
– Pay attention to the learning outcomes in unit outline
– Self-check that you are achieving each one
– Think how each assessment task relates to these
– Time management
– Watch the due dates
– Start work early, submit early
– Networking and community-formation
– Make friends and discuss ideas with them
– Know your tutor, lecturer, coordinator
– Keep them informed, especially if you fall behind
• Don’t wait to get help
– Enjoy the learning!
The University of Sydney Page 35
Advice for doing well in this unit
– To do well in this unit you should
– Organise your time well
– Devote extra 10 hours a week in total to this unit
– Read.
– Think.
– Practice.
“Tell me and I forget, teach me and I may remember,
involve me and I learn.” – Benjamin Franklin
The University of Sydney Page 36
Why Software
Engineering?
The University of Sydney Page 37
• Societies, businesses and governments dependent on SW systems
• Power, Telecommunication, Education, Government, Transport, Finance, Health
• Work automation, communication, control of complex systems
• Large software economies in developed countries
• IT application development expenditure in the US more than $250bn/year1
• Total value added GDP in the US2: $1.07 trillion
• Emerging challenges
• Security, robustness, human user-interface, and new computational platforms
1 Chaos Report, Standish group Report, 2014
2 softwareimpact.bsa.org
Software is Everywhere!
The University of Sydney Page 38
Need to build high quality software systems under resource constraints
• Social
• Satisfy user needs (e.g., functional, reliable, trustworthy)
• Impact on people’s lives (e.g., software failure, data protection)
• Economic
• Reduce cost; open up new opportunities
• Average cost of IT development ~$2.3m, ~$1.3m and ~$434k for large, medium
and small companies respectively3
• Time to market
• Deliver software on-time
3 Chaos Report, Standish group Report, 2014
Why Software Engineering?
The University of Sydney Page 39
What happened?
• European large rocket - 10 years development, ~$7 billion
• Unmanaged software exception resulted from a data conversion
from 64-bit floating point to a 16-bit signed integer
• Backup processor failed straight after using the same software
• Exploded 37 seconds after lift-off
Why did it happen?
• Design error, incorrect analysis of changing requirements, inadequate validation
and verification, testing and reviews, ineffective development processes and
management
http://iansommerville.com/software-engineering-book/files/2014/07/Bashar-Ariane5.pdf
Software Failure - Ariane 5 Disaster
http://iansommerville.com/software-engineering-book/files/2014/07/Bashar-Ariane5.pdf
The University of Sydney Page 40
https://en.wikipedia.org/wiki/List_of_failed_and_overbudget_custom_software_projects
Software Project Failures
Project Duration Cost Failure/Status
e-borders (UK Advanced
passenger Information System
Programme)
2007 - 2014 Over £ 412m
(expected), £742m
(actual)
Permanent failure - cancelled after a
series of delays
Pust Siebel - Swedish Police
case management (Swedish
Police)
2011 - 2014 $53m (actual) Permanent failure – scraped due to poor
functioning, inefficient in work
environments
US Federal Government
Health Care Exchange Web
application
2013 –
ongoing
$93.7m (expected),
$1.5bn (actual)
Ongoing problems - too slow, poor
performance, people get stuck in the
application process (frustrated users)
https://en.wikipedia.org/wiki/List_of_failed_and_overbudget_custom_software_projects
The University of Sydney Page 41
• Essence: difficulties inherent (or intrinsic) in the nature of SW
• Accidents: difficulties related to the production of software
• Most techniques attack the accidents of software engineering
No Silver Bullet - Essence and Accidents in Software Engineering
“There is no single development, in either technology or management technique, which by
itself promises even one order-of-magnitude improvement within a decade in productivity,
in reliability, in simplicity.” ! - Frederick P. Brooks
7 No Silver Bullet - Essence and Accident in Software Engineering - http://www.itu.dk/people/hesj/BSUP/artikler/no-silver-bullit.pdf
Software Engineering - No Silver Bullet7
http://www.itu.dk/people/hesj/BSUP/artikler/no-silver-bullit.pdf
The University of Sydney Page 42
• Complexity
• Many diverse software entities - interactions increase exponentially
• Intrinsic complexity cannot be abstracted - aircraft software, air traffic control
• Conformity
• Arbitrary changes from environment (people, systems) - no unifying principle
• Changeability
• Changing a building model vs. a software
• Stakeholders understanding of software changes
• Invisibility
• Software is intangible (invisible)
• Building model vs software models (UML - 13 diagram types)
Software Engineering - Essence7
The University of Sydney Page 43
What is Software
Engineering?
The University of Sydney Page 44
http://www.purplesoft.com.au/wp-content/uploads/2017/03/software.jpg
What is Software Engineering?
http://www.purplesoft.com.au/wp-content/uploads/2017/03/software.jpg
The University of Sydney Page 45
“An engineering discipline that is concerned with all aspects of software production from the
early stages of system specification through to maintaining it after it is has gone into use.”
• NOT programming/coding! a lot more is involved
• Theories, methods and tools for cost-effective software production
• Technical process, project management and development of tools, methods to
support software production
• System Engineering (Hardware & Software) - software often dominates costs
Software Engineering
The University of Sydney Page 46
Software Engineering
– Theories, methods, tools, techniques and approaches
– Solve concrete SWEN problems
– Increase productivity of the engineering process
– Produce effective software
– Produce efficient software
– Control social and technical aspects in the development process
– Manage complexity, changeability, invisibility and conformity
The University of Sydney Page 47
• The art of managing social, economical and technical factors
• Efficient and effective development processes and management
• Delivering software on-time and on-budget with all the necessary requirements
• The art of analysing and managing complexity
• Ability to understand complex systems
• Apply various abstraction and analytical thinking
“The Roman bridges of antiquity were very inefficient structures. By modern standards,
they used too much stone, and as a result, far too much labour to build. Over the years
we have learned to build bridges more efficiently, using fewer materials and less labour
to perform the same task.” !
- Tom Clancy (The Sum of All Fears)
Software Engineering
The University of Sydney Page 48
• Software processes for managing and developing of SW systems
• Waterfall vs. Incremental and agile software development
• Attributes of good software system
• Maintainability, dependability and security, efficiency and acceptability
• Importance of Dependability and Performance
• Need for specifications and requirements
• Software reuse to save costs
• Careful consideration – Ariane 5 reused software from Arian 4!
Software Engineering Fundamentals
The University of Sydney Page 49
Software Engineering Body of Knowledge
• Software Requirements
• Software Design / Modelling
• Software Construction
• Software Testing
• Software Maintenance
• Software Configuration Management
• Software Engineering Process
• Software Engineering Tools and Methods
• Software Quality
Software Engineering Body of Knowledge (SWEBOK) https://www.computer.org/web/swebok/
https://www.computer.org/web/swebok/
The University of Sydney Page 50
Software
Design/Modelling &
Construction
The University of Sydney Page 51
Software Modelling
• The process of developing conceptual models of a system at different
levels of abstraction
• Fulfil the defined system requirements
• Focus on important system details to deal with complexity
• Object-oriented design approach
• Concepts in the domain problem are modelled as interacting objects
• Using graphical notations (e.g., UML) to capture different views or
perspectives
The University of Sydney Page 52
• Conceptual process to derive general rules and concepts from concrete
information in a certain context
• Analysis and understanding of domain-specific problems
• Decompose large problems into smaller understandable piece
• Language required to break down complexity, i.e., find abstractions
• SW models with different levels of abstraction
• Focus on certain details in each phase of the SW development process
• SW models with different views/perspectives
• Time, structural, requirements, etc.
Software Modelling – The Art of Abstraction
The University of Sydney Page 53
Animal
Dog Cat
Real world
Software world
Abstraction
Software Abstraction – Example
Cat http://s1.thingpic.com/images/ZP/L4FtpQYKNZzCXV8r34PWhqCF.jpeg
Dog https://s7d2.scene7.com/is/image/PetSmart/SV0401_CATEGORY_HERO-Dog-Dog-20160818?$SV0401$
http://s1.thingpic.com/images/ZP/L4FtpQYKNZzCXV8r34PWhqCF.jpeg
https://s7d2.scene7.com/is/image/PetSmart/SV0401_CATEGORY_HERO-Dog-Dog-20160818?$SV0401$
The University of Sydney Page 54
View level
Logical level
(conceptual data
model)
Physical level
(data model)
Data Abstraction – Example
The University of Sydney Page 55
UML Principles
• Graphical notations to visually specify and document design artifacts software
systems using OO concepts
• Industry standard managed by Object Management Group (OMG)
• Is not OO Analysis and Design (OOA&D) or method!
• Is a language for OOA&D communicating visual models of the software being designed
• Is not a skill, but how to design software with different level of abstractions
• Many software diagraming tools, hand sketches are good too
• Combines techniques from data modeling (ER diagrams), business modeling
(workflows), object and component modeling
• Capture system activities (jobs), system components and its interaction, software
entities and its interaction, run-time behavior, external interfaces
The University of Sydney Page 56
UML Principles (Cont.)
• UML is not “Silver Bullet”
• No tool/technique in software will make dramatic order-of-magnitude difference in
productivity, reliability or simplicity
• Design knowledge and thinking in objects is critical
• Three ways to apply UML
• Sketching to explore part of the problem or solution space
• Blueprint: detailed design diagrams for:
• Reverse engineering to visualize and understand existing code
• Forward engineering (code generation)
• Programming language (Model Driven Engineering): executable specification of a system
• “Agile Modeling” emphasizes UML as a sketch
• Not waterfall mindset
The University of Sydney Page 57
UML Diagrams
Structural (static) View
• Static structure of the system
(objects, attributes, operations
and relationships)
Behavioural (dynamic) View
• Dynamic behavior of the system
(collaboration among objects,
and changes to the internal
states of objects)
• Interaction (subset of dynamic
view) - emphasises flow of
control and data
https://en.wikibooks.org/wiki/Introduction_to_Software_Engineering/UML
https://en.wikibooks.org/wiki/Introduction_to_Software_Engineering/UML
The University of Sydney Page 58
The Rational Unified
Process
The University of Sydney Page 59
Iterative and Evolutionary Development
Requirements
Design
Implementation &
Test & Integration
& More Design
Final Integration
& System Test
Requirements
Design
3 weeks (for example)
The system grows
incrementally.
Feedback from
iteration N leads to
refinement and
adaptation of the
requirements and
design in iteration
N+1.
Iterations are fixed in
length, or timeboxed.
Time
Implementation &
Test & Integration
& More Design
Final Integration
& System Test
The University of Sydney Page 60
Rational Unified Process (UP)
• Software development
process utilising iterative
and risk-driven approach to
develop OO software
systems
• Iterative incremental
development
• Iterative evolutionary
development
The University of Sydney Page 61
UP Phases and Disciplines
Sample
UP Disciplines
Business
Modeling
Requirements
Design
Implementation
...
The relative effort in
disciplines shifts
across the phases.
This example is
suggestive, not literal.
incep-
tion
elaboration construction
transi-
tion
...
The University of Sydney Page 62
UP Phases and Disciplines
inc. elaboration construction transition
iteration phase
development cycle
release
A stable executable
subset of the final
product. The end of
each iteration is a
minor release.
increment
The difference
(delta) between the
releases of 2
subsequent
iterations.
final production
release
At this point, the
system is released
for production use.
milestone
An iteration end-
point when some
significant decision
or evaluation
occurs.
The University of Sydney Page 63
UP - Example
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5
20%
2%
re
q
u
ir
e
m
e
n
ts
s
o
ft
w
a
re
30%
5%
re
q
u
ir
e
m
e
n
ts
s
o
ft
w
a
re
50%
8%
90% 90%
20%
10%
requirements workshops
Imagine this will
ultimately be a 20-
iteration project.
In evolutionary iterative
development, the
requirements evolve
over a set of the early
iterations, through a
series of requirements
workshops (for
example). Perhaps
after four iterations and
workshops, 90% of the
requirements are
defined and refined.
Nevertheless, only
10% of the software is
built.
1 2 3 4 5 ... 20
week 1
M T W Th F
week 2
M T W Th F
week 3
M T W Th F
kickoff meeting
clarifying iteration
goals with the team.
1 hour
team agile
modeling &
design,
UML
whiteboard
sketching.
5 hours
start
coding &
testing
a 3-week iteration
de-scope
iteration
goals if
too much
work
final check-in
and code-
freeze for the
iteration
baseline
demo and
2-day
requirements
workshop
next
iteration
planning
meeting;
2 hours
Most OOA/D and
applying UML during
this period
Use-case modeling
during the workshop
• Iterative and evolutionary
analysis and design
• First five iterations of 20
• 3-week iteration
The University of Sydney Page 64
Software Construction / Implementation
• Realisation of design to produce a working software system
• Meet customer requirements
• Design and implementation activities often interleaved
• Agile development to accommodate for changes
• Object-Oriented design and Implementation model
• Encapsulation
• Abstraction
• Reuse
• Maintenance
The University of Sydney Page 65
Software Engineering
http://themetapicture.com/media/funny-software-engineer-comic.jpg
http://themetapicture.com/media/funny-software-engineer-comic.jpg
The University of Sydney Page 1
Software Design and
Construction 1
SOFT2201 / COMP9201
OO Theory in Java
School of Computer Science
Dr. Martin McGrane
The University of Sydney Page 2
Copyright warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been reproduced and communicated to
you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the
Act ).
The material in this communication may be subject
to copyright under the Act. Any further copying or
communication of this material by you may be the
subject of copyright protection under
the Act.
Do not remove this notice.
The University of Sydney Page 3
Overview
– Types
– Encapsulation
– Inheritance
– Variable Binding & Polymorphism
– Virtual Dispatch
– Abstract Classes
– Interfaces
The University of Sydney Page 4
Types in Java
– Overview
– Java is a strongly typed language
– Primitive types: built-in types of the virtual machines
• Cannot be changed by programs
• Have same meaning across computer platforms
– Compositional types
• Interfaces
• Classes
The University of Sydney Page 5
Primitive Types in Java
– Primitive types represent basic data-types
– In-built and cannot be changed in programs
– Integral types
– byte, short, int, long
– Floating point number types
– float, double
– Character type
– char
– Boolean
– boolean
The University of Sydney Page 6
Integral and Floating Types
Type Internal Smallest Value Largest Value
byte 8 bits -128 +127
short 16 bits -32,768 +32,767
int 32 bits -2,147,483,648 +2,147,483,647
long 64 bits -2.3E+18 +2.3E+18
float 32 bits -/+1.4e-45 -/+3.4e+38
double 64 bits -/+4.9e-324 -/+1.7e+308d
The University of Sydney Page 7
Conversion between Primitive Types
– Implicit widening of integral & floating point number types
– byte to short, int, long, float, or double
– short to int, long, float, or double
– char to int, long, float, or double
– int to long, float, or double
– long to float or double
– float to double
– Everything else requires type casts or is not possible
The University of Sydney Page 8
Casting/Widening Matrix
From/To byte char short int long float double boole
an
byte n/a
char (byte) (short) n/a
short (byte) (char) n/a
int (byte) (char) (short) n/a
long (byte) (char) (short) (int) n/a
float (byte) (char) (short) (int) (long) n/a
double (byte) (char) (short) (int) (long) (float) n/a
boolean n/a n/a n/a n/a n/a n/a n/a
The University of Sydney Page 9
Example for Implicit Widening and Casting
…
byte x = 10;
/* implicit widening */
short y = x;
long z = x;
float f = x;
/* casting */
byte p = (byte) z;
short q = (short) f;
The University of Sydney Page 10
Silent Failure of Types
– Example:
– Integer overflow occurs for variable i
– Type system cannot prevent this at compile-time
– weak notion of correctness
…
int i = Integer.MAX_VALUE;
System.out.println(i);
i = i + 1;
System.out.println(i);
…
The University of Sydney Page 11
Operators and Primitive Types
– Special rules for results of operators
– Type inference deduces type of expressions
– Example:
…
byte a = 1;
byte b = 2;
byte c = a + b; /* that gives an error */
byte d = a – b; /* that gives an error */
…
The University of Sydney Page 12
Operators and Primitive Types
Java Language Specification
5.6.2. Binary Numeric Promotion
…
2.Widening primitive conversion (§5.1.2) is applied to convert either or both
operands as specified by the following rules:
•If either operand is of type double, the other is converted to double.
•Otherwise, if either operand is of type float, the other is converted to float.
•Otherwise, if either operand is of type long, the other is converted to long.
•Otherwise, both operands are converted to type int.
https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.2
The University of Sydney Page 13
Primitive Types
– Basic data-types
– Behave the same on all platforms running Java’s virtual machine
– Primitive Types are not classes nor interfaces
– Primitive Types are building blocks for more complex types
– Beside storing of the actual value there is very little additional
overhead
– Note that classes have extra information to keep of dynamic runtime
info
– Operations on primitive data-types are very efficient
The University of Sydney Page 14
Classes in Java
– Classes are types
– Composite type consisting of fields(=state) and methods(=behavior)
– Class Abstraction
– Separate class implementation from the use of a class
– User of a class does not need to know the implementation / just the
public methods
– The implementor provides the implementation of the class
– The details are encapsulated and hidden from the user
– Class creates objects (instantiate)
– Object communicates with each other via methods
The University of Sydney Page 15
Classes
– A basic class has a name, fields, and methods:
Rectangle
width
height
area ( )
Name of Class
Fields
Methods
The University of Sydney Page 16
Classes (cont’d)
– The basic syntax for a class is
– Example:
class
{
}
class Rectangle
{
}
The University of Sydney Page 17
Adding Fields: Class Rectangle with Fields
– Add fields
– The fields (data) are also called the instance variables
– Fields can be
– Primitive types (int, bool, etc.)
– References to other class instances
public class Rectangle {
public double width, height;
}
The University of Sydney Page 18
Adding Methods
– To change / retrieve state of a class, methods are necessary
– Methods are declared inside the body
– Methods are messages in an object-oriented programming sense
– A return type must be specified
– A list of arguments with their types must be specified
– The general form of a method declaration is:
type Method (argument-list) {
Method-body;
}
The University of Sydney Page 19
Adding Methods to Rectangle
public class Rectangle {
public double width, height;
public void setWidth(double w) {
width = w;
}
public void setHeight(double h) {
height = h;
}
public double area() {
return width * height;
}
}
Method Body
Fields
The University of Sydney Page 20
Mutators
– Methods that change the state of a class object are called mutators
– Example:
– Gives clients of the class write access to the state
public void setWidth(double w) {
width = w;
}
public void setHeight(double h) {
height = h;
}
The University of Sydney Page 21
Accessor
– Methods that read the state of a class object are called
accessors
– Example:
– Gives clients of the class read access to the state
public double area() {
return width * height;
}
The University of Sydney Page 22
Constructors
– Special method in class whose task is to initialise fields of the class
– The name is the same name as class
– Constructors are invoked whenever an object of that class is created
– It is called ‘constructor’ because it constructs values of data members.
– A constructor cannot return a value
– There can be several constructors for a class
– Default constructor with no parameters
– Parameterised constructors
The University of Sydney Page 23
Example: Default Constructor
– Default constructor
– Java has a synthesised default constructor when not specified
public class Rectangle {
public double width, height;
// default constructor
public Rectangle() {
width = 1.0;
height = 1.0;
}
}
The University of Sydney Page 24
Example: Parameterised Constructor
– Parameterised constructor:
public class Rectangle {
public double width, height;
// parameterised constructor
public Rectangle(double w, double h) {
width = w;
height = h;
}
}
The University of Sydney Page 25
Example: Multiple Constructors
– Default and parameterised constructor (overloading)
public class Rectangle {
public double width, height;
// default constructor
public Rectangle() {
width = 1.0;
height = 1.0;
}
// parameterised constructor
public Rectangle(double w, double h) {
width = w;
height = h;
}
}
The University of Sydney Page 26
Creating Instances of a Class
– Objects are created dynamically using the new keyword.
– The new operator creates a new object on the heap
– The object will be selected as a candidate if not further used
– The object becomes a candidate for automatic garbage collection
– Garbage collection kicks in periodically and releases candidates
– developers don’t need to delete their own objects
– Example:
– Define a reference variable X of type class that points to a new
instance
The University of Sydney Page 27
Example: Creating Instances of a Class
– rec1 and rec2 refer to Rectangle objects
– First instance calls default constructor
– Second instance calls parameterised constructor
rec2 = new Rectangle(10,1);rec1 = new Rectangle();
The University of Sydney Page 28
Copy Constructor
– Java has no copy constructor
– We can simulate copy constructor by having a constructor with
objects of same type as argument
– All classes are derived from class Object
– Object has the method clone()
The University of Sydney Page 29
Example: Copy Constructor
– Copy constructor
public class Rectangle {
public double width, height;
// copy constructor
public Rectangle(Rectangle o) {
width = o.width;
height = o.height;
}
}
The University of Sydney Page 30
Accessing Fields and Methods
– Access is done via the . operator
– Access to field and methods of an instance in the same style
– Access modifier is important
– public/protected/private
– Controls whether access is permitted at client or member level
The University of Sydney Page 31
Example: Accessing fields / methods
– Using object methods:
Rectangle rec = new Rectangle();
rec.width = 1.0;
rec.height = 100.0;
double area = rec.area();
send ‘message’ area to an
instance of type Rectangle
which rec is referring to
The University of Sydney Page 32
Access Modifiers
– Access modifiers provide encapsulation for object-oriented
programming
– Protect state from client
– Access modifiers work on different levels:
– Class level
– Member level
– Client level
The University of Sydney Page 33
Access Modifier: public
– A class that is labeled as public is accessible to all other classes
inside and outside a package
package com.foo.goo;
public class test1 {
public void test();
}
package com.foo.hoo;
import com.foo.goo;
public class test2 {
public void test(){
test1 x = new test1();
}
}
The University of Sydney Page 34
Access Modifier: public
– A class marked as public is accessible to all classes with the
import statement
– There is no need for import statement if a public class is used in
the same package
The University of Sydney Page 35
Access Modifier: default
– Default access is a class definition with no specified access
qualifier
– Classes marked with default access are visible only in package
but not outside of package
– Note that protected and private classes are not available for
packages
The University of Sydney Page 36
Member access modifiers for methods and fields
– Public
– Accessible by client, package, class, and sub-classes
– Protected
– Accessible by package, class, and sub-classes
– ‘Default’
– Accessible by class and package
– Private
– Accessible by class itself only
The University of Sydney Page 37
Example: Member access modifiers
– Example: public
public class Rectangle {
public double width, height;
}
// client can access state
Rectangle x = new Rectangle();
x.width = 100;
x.height = 100;
The University of Sydney Page 38
Example: Member access modifiers
– Example: protected
public class Rectangle {
protected double width, height;
}
// client cannot access state
Rectangle x = new Rectangle();
x.width = 100; // access error!
x.height = 100; // access error!
The University of Sydney Page 39
Example: Member
access modifiers
– Example: private
public class Rectangle {
private double width, height;
Rectangle(double w, double h) {
width = w; // access is ok
height = h; // access is ok
}
}
public class Square extends Rectangle {
Square(double w) {
super.Rectangle(w,w);
}
void setWidth(double w) {
super.width = w; // access error!
super.height = w; // access error!
}
}
The University of Sydney Page 40
Encapsulation
– Wrap data/state and methods into a class as a single unit
– Multiple instances can be generated
– Protect state via setter (mutator)/getter (accessor) methods
The University of Sydney Page 41
Sub-Classes
– Classes permit inheritance
– Methods and fields from a super-class can be inherited
– Ideal for software-engineering
– Reuse of code
– Java uses “extends” keyword for extending from existing class
– Single-inheritance paradigm
– Class hierarchy has a tree structure
– If no super-class is specified, default class Object becomes
super-class
The University of Sydney Page 42
Inheritance
– Sub-class inherits from super-class: methods, variables, …
– Reuse structure and behavior from super-class
– Single inheritance for classes
The University of Sydney Page 43
Variable Binding, Polymorphism
– Object (on heap) has single type when created
– Type cannot change throughout its lifetime
– Reference variables point to null or an object
– Type of object and type of reference variable may differ
– e.g., Shape x = new Rectangle(4,2);
– Understand the difference
– Runtime type vs compile-time type
– Polymorphism:
– Reference variable may reference differently typed object
– Must be a sub-type of
The University of Sydney Page 44
Virtual Dispatch
– Methods in Java permit a late binding
– Reference variable and its type does not tell which method is
really invoked
– The type of reference variable and class instance may differ
– Class variables may override methods of super classes
– The method invoked is determined by the type of the class
instance
– Binding is of great importance to understand OO
The University of Sydney Page 45
Example: Virtual Dispatch
– Example:
public class Shape /* extends Object */ {
double area() { }
}
public class Rectangle extends Shape {
double area() { }
}
…
Shape x = new Shape();
Shape y = new Rectangle();
double a1 = x.area() // invokes area of Shape
double a2 = y.area() // invokes area of Rectangle
The University of Sydney Page 46
Abstract Classes
– Method implementations may be deferred to sub-classes
– Requires own key-word abstract for class/method
– No instance of an abstract class can be generated
The University of Sydney Page 47
Interfaces
– Java has no multi-inheritance
– Interface are a way out (introduction of multi-inheritance via the back-door)
– Interfaces are a class contract that ensures that a class implements a set of
methods.
– Interfaces can inherit from other interfaces
– Ensures that a class has a certain set of behavior
– Interfaces are specified so that they form a directed acyclic graph
– Methods declared in an interface are always public and abstract
– Variables are permitted if they are static and final only
The University of Sydney Page 48
Example: Interface
// definition of interface
public interface A {
int foo(int x);
}
// class X implements interface A
class X implements A {
int foo(int x) {
return x;
}
}
The University of Sydney Page 49
Example: Interface
– Inheritance in interfaces
– Interface B has methods foo() and hoo()
// definition of interface
public interface A {
int foo(int x);
}
public interface B extends A{
int hoo(int x);
}
The University of Sydney Page 1
Software Design and
Construction 1
SOFT2201 / COMP9201
UML Modeling
School of Computer Science
Dr. Martin McGrane
The University of Sydney Page 2
Copyright warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been reproduced and communicated to
you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the
Act ).
The material in this communication may be subject
to copyright under the Act. Any further copying or
communication of this material by you may be the
subject of copyright protection under
the Act.
Do not remove this notice.
The University of Sydney Page 3
Agenda
– UML Modeling
– UML Use Case Diagrams
– UML Class Diagrams
– UML Interaction Diagrams
– Case Study: Next Gen Point-of-Sale (POS) System
– Brief Introduction
– Self learning details
The University of Sydney Page 4
Software Modelling
• The process of developing conceptual models of a system at different
levels of abstraction
• Fulfil the defined system requirements
• Focus on important system details to deal with complexity
• Using graphical notations (e.g., UML) to capture different views or
perspectives
• There are three ways to apply UML
• Blueprint: detailed design diagrams for:
• Reverse engineering to visualise and understand existing code
• Forward engineering (code generation)
The University of Sydney Page 5
UML Diagrams
https://en.wikibooks.org/wiki/Introduction_to_Software_Engineering/UML
Structural (static) View
• Static structure of the system
(objects, attributes, operations
and relationships)
Behavioural (dynamic) View
• Dynamic behavior of the system
(collaboration among objects,
and changes to the internal
states of objects)
• Interaction (subset of dynamic
view) – emphasises flow of
control and data
https://en.wikibooks.org/wiki/Introduction_to_Software_Engineering/UML
The University of Sydney Page 6
Use Case Diagrams
Craig Larman. 2004. Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and
Iterative Development (3rd Edition).
1. Why we need Use Case Diagrams?
2. What is a Use Case?
3. How can we draw Use Case Diagrams?
The University of Sydney Page 7
Rational Unified Process (UP)
• Software development
process utilising iterative
and risk-driven approach to
develop OO software
systems
• Iterative incremental
development
• Iterative evolutionary
development
The University of Sydney Page 8
Business Modelling,
Requirements and
Designs in RUP/UP*
Operation:
enterItem(…)
Post-conditions:
– . . .
Operation Contracts
Sale
date
. . .
Sales
LineItem
quantity
1..*1 . . .
. . .
Domain Model
Use-Case Model
Design Model
: Register
enterItem
(itemID, quantity)
: ProductCatalog
spec = getProductSpec( itemID )
addLineItem( spec, quantity )
: Sale
objects, attributes,
associations
Require-
ments
Business
Modeling
Design
Sample UP Artifact Relationships
: System
enterItem
(id, quantity)
Use Case Text
System Sequence Diagrams
make
NewSale()
system
events
Cashier
Process
Sale
: Cashier
use
case
names
system
operations
Use Case Diagram
Vision
Supplementary
Specification
Glossary
scope, goals,
actors, features
terms, attributes,
validation
non-functional reqs,
quality attributes
requirements
Process Sale
1. Customer
arrives …
2. Cashier
makes new
sale.
3. …
*RUP/UP: Rational Unified Process,
Lecture 1 pp. 59–64
Use Cases and Use
Case Diagrams
The University of Sydney Page 9
Use Cases
• Use case: “specifies a set of behaviors performed by a system, which yields an
observable result that is of value for Actors or other stakeholders of the system”*
• It capture what a system supposed to do (system’s requirements)
• Text documents not diagrams
• Primary part of the use case model
• Scenario (use case instance): specific sequence of action and interactions
between actors and the system
• One particular story of using a system (e.g., successfully purchasing items with cash)
• Use case model: set of all written use cases (a model of the system functionality and
environment)
• Defined within the Requirements discipline in the UP
• Not the only requirement artefact – business rules, supplementary specifications, etc
* OMG Unified Modeling Language, version 2.5.1, Dec. 2017 https://www.omg.org/spec/UML/2.5.1
https://www.omg.org/spec/UML/2.5.1
https://www.omg.org/spec/UML/2.5.1
The University of Sydney Page 10
Use Cases – Common Formats
• Brief: one-paragraph summary, usually of the main success scenario
• During early requirements analysis to get quick subject and scope
• Casual: Informal paragraph format; multiple paragraphs that cover various
scenarios
• During early requirements analysis to get quick subject and scope
• Full-dressed: all steps and variations are written in detail and there are
supporting sections; e.g., pre-conditions, success guarantee
• After many use cases have been identified and written in brief format
* OMG Unified Modeling Language, version 2.5.1, Dec. 2017 https://www.omg.org/spec/UML/2.5.1
https://www.omg.org/spec/UML/2.5.1
https://www.omg.org/spec/UML/2.5.1
The University of Sydney Page 11
Use Cases – Full-dressed Template
Use case section Comment
Use case name Start with a verb
Scope The system under design
Level “user-goal” or sub-function
Primary actor Calls on the system to deliver its services
Stakeholders and interests Who cares about this UC and what do they earnt
Preconditions What must be true on start
Success guarantee What must be true on successful completion
Main success scenario Typical unconditional happy path scenario
Extensions Alternate scenarios of success or failure
Special requirements Related non-functional requirement
…..
The University of Sydney Page 12
Use Case Diagrams
• UML graphical notations that help to capture use cases (system’s boundaries
and interactions and relationships)
• Subject: system under consideration to which the use case applies
• Actor: role that interact with the subject/system (e.g., end user, customer, supplier,
another system)
• Use case: describes functionality of the system
• Association: relationship between an actor and a use case (an actor can use certain
functionality of the system)
• «include» indicates the behavior of the included use case is included in the
behavior of the including use case
* OMG Unified Modeling Language, version 2.5.1, Dec. 2017 https://www.omg.org/spec/UML/2.5.1
https://www.omg.org/spec/UML/2.5.1
https://www.omg.org/spec/UML/2.5.1
The University of Sydney Page 13
Use Case Diagram – UML Notations
NextGen
Process Sale
. . .
Cashier
Show computer system actors
with an alternate notation to
human actors.
primary actors on
the left
supporting actors
on the right
For a use case context
diagram, limit the use cases to
user-goal level use cases.
«actor»
Payment
Authorization
Service
NextGen
Process Sale
«system»
Payment
Authorization
Service
…
«actor»
Payment
Authorization
Service
Some UML alternatives to
illustrate external actors that
are other computer systems.
The class box style can be
used for any actor, computer or
human. Using it for computer
actors provides visual
distinction.
Payment
Authorization
Service
The University of Sydney Page 14
Use Case Diagrams – Tools
https://www.lucidchart.com/pages/examples/uml_diagram_tool
• There are many tools to aid drawing UML diagrams
• Tools are means to make your life easier
• You can also sketch diagrams using pen-and-paper or white board
https://www.lucidchart.com/pages/examples/uml_diagram_tool
The University of Sydney Page 15
Class Diagrams
Structural Diagrams
Craig Larman. 2004. Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and
Iterative Development (3rd Edition).
The University of Sydney Page 16
Class Diagram – Notations
• Common compartments: classifier
name, attributes and operations
• Package name
• <
• Class hierarchy – inheritance
• Dependency
• Association and multiplicity
• Optional and default elements
The University of Sydney Page 17
Class Diagram – Perspectives
Conceptual Perspective
(domain model)
Raw UML class diagram
notation used to visualize
real-world concepts.
Specification or
Implementation
Perspective
(design class diagram)
Raw UML class diagram
notation used to visualize
software elements.
2
Die
faceValue : int
getFaceValue() : int
roll()
DiceGame
die1 : Die
die2 : Die
play()
DiceGame Die
faceValue
Includes 21
• Conceptual: describes key
concepts in the problem
domain. Use in business
modeling for OO analysis
• Specification: describes
software components with
specification and interfaces
• Implementation: describes
software implementation in a
particular programming
language (e.g., Java)
The University of Sydney Page 18
Class Diagrams – UML Attributes
Attribute Text
Visibility : type {property string}
Visibility + (public), – (private)
Attributes are assumed private if no
visibility sign shown
Attribute-as-association
Arrow pointing from the source to the
target
Multiplicity and ‘rolename’ (currentSale) at
the target
No association name
Attribute text and as-association
• Not popular
Register
…
…
Sale
…
…
1
Register
currentSale : Sale
…
Sale
…
…
using the attribute
text notation to
indicate Register has
a reference to one
Sale instance
using the association notation to indicate
Register has a reference to one Sale instance
OBSERVE: this style
visually emphasizes
the connection
between these classes
currentSale
Register
currentSale : Sale
…
Sale
…
…
1
thorough and
unambiguous, but some
people dislike the
possible redundancy
currentSale
The University of Sydney Page 19
Class Diagrams – Attribute Examples
Read-only Attributes with initialisation, and optional values
Sale
– dateTime : Date
– / total : Money
Private visibility
attributes
Math
+ pi : Real = 3.14 {readOnly}
Public visibility readonly
attribute with initialization
Person
firstName
middleName : [0..1]
lastName
Optional value
The University of Sydney Page 20
Class Diagrams – Operations
Visibility Name (parameter-list) : return-type {property-string} (UML 1)
Visibility Name (parameter-list) {property-string} (UML 2)
• Not a method, but declaration with a name, parameters, return type, exception list, and
possibly a set of constraints of pre-and post-conditions
• Operations are public by default, if no visibility shown
• Operation signature in a programming language is allowed, e.g.,
+ getPlayer (name : String) : Player {exception IOException}
Public Player getPlayer(String name) throws IOException
The University of Sydney Page 21
Class Diagrams – Methods
• Implementation of an operation, can be specified in:
• Class diagrams using UML note symbol with stereotype symbol «method»
• Mixing static view (class diagram) and dynamic view (method implementation)
• Good for code generation (forward engineering)
• Interaction diagrams by the details and sequence of messages
Register
…
endSale()
enterItem(id, qty)
makeNewSale()
makePayment(cashTendered)
«method»
// pseudo-code or a specific language is OK
public void enterItem( id, qty )
{
ProductDescription desc = catalog.getProductDescription(id);
sale.makeLineItem(desc, qty);
}
The University of Sydney Page 22
UML Keywords
• Textual adornment to categorise a model element
• Using «» or { }
• UML 2 the brackets («») are used for keywords and stereotype
Keyword Meaning Example usage
«interface» Classifier is an interface In class diagram, above classifier name
{abstract} Abstract element; can’t be instantiated In class diagrams, after classifier name or
operation name
{ordered} A set of objects have some imposed
ordered
In class diagrams, at an association end
The University of Sydney Page 23
UML Stereotypes
• Stereotypes allow refinement (extension) of an existing modeling concept
• Defined in UML Profile
• UML profile: group of related model elements allow customising UML models
for a specific domain or platform
• Extends UML’s «metaclass» Element
«stereotype»
Authorship
author: String
status : String
UML extension
relationship to a basic
UML metamodel term –
Element
«authorship»
author = “craig”
status = “tested”
«metaclass»
Element
…
«authorship»
Square
…
using the stereotype
a tool will probably allow a popup to fill in the tag values,
once an element has been stereotyped with «authorship»
declaring the stereotype
• UML note symbol
• Has no semantic impact
Specify a constraint
The University of Sydney Page 24
Constraints
• Restriction/condition on a UML elements described in a natural or a formal
language (Object Constraint Language (OCL))
• Different ways to represent constraints
The University of Sydney Page 25
Generalisation, Abstract Classes & Operations
“Generalisation – a taxonomic relationship between a more general classifier and a more
specific classifier. Each instance of the specific classifier is also an indirect instance of the
general classifier. Thus, specific classifiers indirectly has features of the more general
classifiers.” [OMG2003]
• Generalisation implies inheritance in design class diagram (software
perspective) but not in the domain model (conceptual perspective)
• Classes and operations with {abstract} tag are abstract
• Classes and operations with {leaf} are final (cannot be overridden in the sub-classes)
The University of Sydney Page 26
Composition
• Composition, or composite aggregation, relationship implies:
• Instance of the part (e.g., Square) belongs to only one composite instance at a time
(e.g., one board)
• The part must always belong to a composite
• The composite is responsible for the creation and deletion of its parts (by itself or
by collaborating with other objects)
The University of Sydney Page 27
Associations
• Relationship between classifiers where
logical or physical link exists among
classifier’s instances
• May implemented differently; no certain
construct linked with association
• Notations:
• Association name (meaningful)
• Multiplicity
• Direction arrow
SaleRegister
Records-current
0..11
association name multiplicity
-“reading direction arrow”
-it has no meaning except to indicate direction of
reading the association label
-often excluded
The University of Sydney Page 28
Associations – Multiplicity
• Multiplicity: number of instances involved
in the relationship (association)
• Communicates domain constraints that will
be implemented
• Multiplicity focuses on the relationship at a
particular moment, rather than over a
span of time
• “In countries with monogamy laws, a
person can be Married-to only one other
person at any particular moment, even
though over a span of time, that same
person may be married to many persons.”
Multipl
icity
Meaning (number of
participating instances)
* Zero or more; many
0..1 Zero or one
1..* One or more
1..n One to n
n Exactly n
n, m, k Exactly n, m or k
The University of Sydney Page 29
Association Class
• Modelling an association as a class (with attributes, operations & other features)
• A Company Employs many Persons
• Employs → Employment class with attributes salary and startDate
salary
startDate
Employment
Employs
Company Person**
a person may have
employment with several
companies
The University of Sydney Page 30
Dependency
• A dependency exists between two elements if changes to the definition of one
element (the supplier) may cause changes to the other (the client)
• Various reason for dependency
• Class send message to another
• One class has another as its data
• One class mention another as a parameter to an operation
• One class is a superclass or interface of another
The University of Sydney Page 31
When to show dependency?
• Be selective in describing dependency
• Many dependencies are already shown in another format
• To depict global, parameter variable, local variable and static-method
• To show how changes in one element might alter other elements
• There are many varieties of dependency, use keywords to differentiate them
• Different tools have different sets of supported dependency keywords:
<
<
<
<
The University of Sydney Page 32
Dependency Example
System
…
runFinalization()
…
Foo
…
doX()
…
the doX method invokes the runFinalization
static method, and thus has a dependency on
the System class
The University of Sydney Page 33
UML Interaction
Diagrams
Dynamic (Behavioural) Diagrams
Craig Larman. 2004. Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative
Development (3rd Edition).
The University of Sydney Page 34
UML Interaction Diagrams
• One of the dynamic (behavioural) diagrams which consists of diagrams including
Sequence and Communication diagram
: A myB : B
doTwo
doOne
doThree
Communication diagrams: objects’
interactions are illustrated in a
graph/network format
Sequence diagrams: illustrate sequence/time-
ordering of messages in a fence format (each object
is added to the right)
: A
myB : B
1: doTwo
2: doThree
doOne
The University of Sydney Page 35
Sequence Diagrams: Classes/Objects
• Participants in interactions (class instances, lifeline boxes)
sales:
ArrayList
:Sale s1 : Sale
lifeline box representing an
instance of an ArrayList class,
parameterized (templatized) to
hold Sale objects
lifeline box representing an
unnamed instance of class Sale
lifeline box representing a
named instance
sales[ i ] : Sale
lifeline box representing
one instance of class Sale,
selected from the sales
ArrayList
x : List
«metaclass»
Font
lifeline box representing the class
Font, or more precisely, that Font is
an instance of class Class – an
instance of a metaclass
related
example
List is an interface
in UML 1.x we could not use an
interface here, but in UML 2, this (or
an abstract class) is legal
Actual lifeline of a
participating object
(solid or dashed)
The University of Sydney Page 36
Sequence Diagrams: Messages
• Standard message syntax in UML
ReturnVar = message (parameter : parameterType) : returnType
• Some details may be excluded.
Examples:
Initialise(code)
descrp = getProductDescription(id)
descrp = getProductDescription(id) : ProductDescription
• The time ordering from top to bottom of lifelines
: Register : Sale
doA
doB
doX
doC
doD
typical sychronous message
shown with a filled-arrow line
a found message
whose sender will not
be specified
execution specification
bar indicates focus of
control
The University of Sydney Page 37
Sequence Diagrams: Messages
Message reply/return
1. Standard reply/return message syntax
returnVar = message (parameter)
2. Reply/return message line at the end of
execution bar
: Register : Sale
d1 = getDate
getDate
doX
aDate
: Register
doX
clear
Messages to “Self”
Using nested execution bar
The University of Sydney Page 38
Sequence Diagrams: Objects Creation/Destruction
Object Creation
Read as:
“Invoke the new operator and call the constructor”
Message name is optional
Object Destruction
Explicit destruction to indicate object
is no longer useable (e.g., closed
database connection)
: Register : Sale
makePayment(cashTendered)
: Payment
create(cashTendered)
authorize
note that newly created
objects are placed at their
creation “height” : Sale
: Payment
create(cashTendered)
…
the «destroy» stereotyped
message, with the large
X and short lifeline
indicates explicit object
destruction
«destroy»
X
The University of Sydney Page 39
Sequence Diagrams: Frames
enterItem(itemID, quantity)
: B
endSale
a UML loop
frame, with a
boolean guard
expression
description, total
makeNewSale
[ more items ]loop
: A
• Diagram frames in UML sequence diagrams
• Support conditional and looping construct
The University of Sydney Page 40
Sequence Diagrams: Frames
• Common frame operators
Frame operator Meaning
Alt Alternative fragment for mutual exclusion conditional logic expressed in the
guards
Loop Loop fragment while guard is true
Opt Optional fragment that executes if guard is true
Par Parallel fragments that execute in parallel
Region Critical region within which only one thread can run
The University of Sydney Page 41
Sequence Diagrams: Conditional Messages
calculate
: Bar
yy
xx
[ color = red ]opt
: Foo
public class Foo {
Bar bar = new Bar ( );
…
public void ml ( ) {
bar.xx( );
if (colour.equals(”red”))
bar.calculate( );
bar.yy( );
}
}
The University of Sydney Page 42
Sequence Diagrams: Conditional Messages
: B: A
calculate
doX
: C
calculate
[ x < 10 ]alt
[ else ]
Mutually exclusive conditional messages
The University of Sydney Page 43
Sequence Diagrams: Nesting of Frames
calculate
: Bar
xx
[ color = red ]opt
: Foo
loop(n)
The University of Sydney Page 44
Class Diagrams: Relationship to Interaction Diagrams
• Interaction diagrams illustrates how objects interact via messages (dynamic behavior)
• Classes and their methods can be derived
• E.g., Register and Sale classes from makePayment sequence diagram
: Register : Sale
makePayment(cashTendered)
makePayment(cashTendered)
Register
...
makePayment(…)
...
Sale
...
makePayment(…)
...
1
currentSale
messages in interaction
diagrams indicate operations
in the class diagrams classes
identified in the
interaction
diagrams are
declared in the
class diagrams
• Agile modelling practice:
draw diagrams
concurrently as dynamic
and static views
complement each other
during the design process
The University of Sydney Page 45
Software Modelling Case
Study
NextGen POS software modeling
Craig Larman. 2004. Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and
Iterative Development (3rd Edition).
The University of Sydney Page 46
Next Gen Point-Of-Sale (POS) System
• A POS is a computerised application used (in part) to
record sales and handle payments
– Hardware: computer, bar code scanner
– Software
– Interfaces to service applications: tax calculator, inventory control
– Must be fault-tolerant (can capture sales and handle cash payments even if remote
services are temporarily unavailable
– Must support multiple client-side terminals and interfaces; web browser terminal, PC with
appropriate GUI, touch screen input, and Wireless PDAs
– Used by small businesses in different scenarios such as initiation of new sales, adding
new line item, etc.
The University of Sydney Page 47
Next Gen POS Analysis
Scope of OOA & D and Process Iteration
Craig Larman. 2004. Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and
Iterative Development (3rd Edition).
The University of Sydney Page 48
Next Gen POS – Scope (Analysis & Design)
User Interface
Sale Payment
Logging ... Database Access ...
application
logic layer
other layers or
components
minor focus
explore how to connect to
other layers
primary focus
of case studies
explore how to
design objects
secondary
focus
The University of Sydney Page 49
Iteration and Scope – Design and Construction
Iteration 1
Iteration 2
Iteration 3
Introduces just those
analysis and design
skills related to
iteration one.
Additional analysis and
design skills introduced.
Likewise.
The University of Sydney Page 50
Next Gen POS:
From Analysis to Design
Operation:
enterItem(…)
Post-conditions:
- . . .
Operation Contracts
Sale
date
. . .
Sales
LineItem
quantity
1..*1 . . .
. . .
Domain Model
Use-Case Model
Design Model
: Register
enterItem
(itemID, quantity)
: ProductCatalog
spec = getProductSpec( itemID )
addLineItem( spec, quantity )
: Sale
Require-
ments
Business
Modeling
Design
Sample UP Artifact Relationships
: System
enterItem
(id, quantity)
Use Case Text
System Sequence Diagrams
make
NewSale()
system
events
Cashier
Process
Sale
: Cashier
use
case
names
system
operations
Use Case Diagram
Vision
Supplementary
Specification
Glossary
parameters and
return value details
starting events to design for
Process Sale
1. Customer
arrives ...
2. Cashier
makes new
sale.
3. ...
Requirements Analysis (OOA)
Business modelling – domain models
Use case diagrams
Use case description
System Sequence Diagrams
Design (OOD)
Sequence diagrams
Class diagrams
The University of Sydney Page 51
Self Learning Case Study
1. Use Cases
2. Use Case Diagram
3. Domain Model
4. Class Diagram
5. Interaction Diagram
Craig Larman. 2004. Applying UML and Patterns: An Introduction to Object-Oriented Analysis and
Design and Iterative Development (3rd Edition).
The University of Sydney Page 1
Software Design and
Construction 1
SOFT2201 / COMP9201
Software Design Principles
School of Computer Science
Dr. Martin McGrane
The University of Sydney Page 2
Copyright warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been reproduced and communicated to
you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the
Act ).
The material in this communication may be subject
to copyright under the Act. Any further copying or
communication of this material by you may be the
subject of copyright protection under
the Act.
Do not remove this notice.
The University of Sydney Page 3
How do we know if the
design of software is
good?
The University of Sydney Page 4
Agenda
– Design Smells
– SOLID
– A list of excellent design principles
– GRASP
– Designing objects with Responsibilities
The University of Sydney Page 5
Design Smells
The University of Sydney Page 6
Design Smells
“Structures in the design that indicate violation of fundamental design principles and
negatively impact design quality” – Girish Suryanarayana et. Al. 2014
Girish Suryanarayana, et. al. (2014). "Refactoring for software design smells: Managing technical debt"
http://www.codeops.tech/blog/linkedin/what-causes-design-smells/
• Poor design decision that make the design
fragile and difficult to maintain
• Bugs and unimplemented features are not
automatically design smells
The University of Sydney Page 7
Common Design Smells
• Missing abstraction: clumps of data or encoded strings are used instead of creating an
abstraction
• Multifaceted abstraction: an abstraction has multiple responsibilities assigned to it
• Insufficient modularisation: an abstraction has not been completely decomposed, and
a further decomposition could reduce its size, implementation complexity, or both
• Cyclically-dependent modularisation: two or more abstractions depend on each other
directly or indirectly (creating tightly-coupling abstractions)
• Cyclic hierarchy: a super-type in a hierarchy depends on any of its subtypes
Girish Suryanarayana, et. al. (2014). "Refactoring for software design smells: Managing technical debt"
The University of Sydney Page 8
Summary of Common Symptoms Design Smells
• Rigidity (difficult to change)
• Fragility (easy to break)
• Immobility (difficult to reuse)
• Viscosity (difficult to do the right thing)
• Needless Complexity (overdesign)
• Needless Repetition (mouse abuse)
• Opacity (disorganised expression)
Girish Suryanarayana, et. al. (2014). "Refactoring for software design smells: Managing technical debt"
The University of Sydney Page 9
Symptoms Design Smells
• Rigidity (difficult to change): the system is hard to change because every change
forces many other changes to other parts of the system
• A design is rigid if a single change causes a cascade of subsequent changes in
dependent modules
• Fragility (easy to break): Changes cause the system to break in places that have no
conceptual relationship to the part that was changed
• Fixing those problems leads to even more problems
• As fragility of a module increases, the likelihood that a change will introduce
unexpected problems approaches certainty
• Immobility (difficult to reuse): It is hard to detangle the system into components that
can be reused in other systems
.
The University of Sydney Page 10
Symptoms Design Smells
• Viscosity: Doing things right is harder than doing things wrong
• Software: when design-preserving methods are more difficult to use than the others
(hacks), the design viscosity is high (easy to do the wrong thing but difficult to do
the right thing)
• Environment: when development environment is slow and inefficient.
• Compile times are very long, developers try to make changes that do not force
large recompiles, even such changes do not preserve the design
• Needless Complexity: when design contains elements that are not useful.
• When developers anticipate changes to the requirements and put facilities in
software to deal with those potential changes.
.
The University of Sydney Page 11
Symptoms Design Smells
• Needless Repetition:
• Developers tend to find what they think relevant code, copy and paste and change
it in their module
• Code appears over and over again in slightly different forms, developers are
missing an abstraction
• Bugs found in repeating modules have to be fixed in every repetition
• Opacity: tendency of a module to be difficult to understand
• Code written in unclear and non-expressive way
• Code that evolves over time tends to become more and more opaque with age
• Developers need to put themselves in the reader’s shoes and make appropriate
effort to refactor their code so that their readers can understand it
.
The University of Sydney Page 12
SOLID Design Principles
The University of Sydney Page 13
SOLID: Single Responsibility
Every class should have a single responsibility and that responsibility should be entirely
met by that class
The University of Sydney Page 14
SOLID: Open/Closed
Open for extension but not for mutilation
modification
Have you ever written code that you don’t want others
to mess with?
Have you ever wanted to extend something that
you can’t?
The Open/Closed principle is that you should be able to extend
code without breaking it. That means not altering superclasses when
you can instead add a subclass.
New subtypes of a class should not require changes to the superclass
The University of Sydney Page 15
SOLID: Open/Closed
This really isn’t a good design: every
time a new object is introduced to be
drawn, the base class has to be changed
The University of Sydney Page 16
SOLID: Open/Closed
This is much better: each item has its own
draw method which is called at runtime
through polymorphism mechanisms
The University of Sydney Page 17
SOLID: Liskov Substitution Principle
• In 1987, Barbara Liskov introduced her idea of strong behavioural subtyping, later
formalised in a 1994 paper with Jeannette Wing and updated in a 1999 technical
report as
Let q(x) be a property provable about objects x of type T . Then q(y) should be
provable for objects y of type S where S is a subtype of T .
• This defines required behaviours for mutable(changeable) objects: if S is a subtype of
T , then objects of type T in a program may be replaced with objects of type S without
altering any of the desirable properties of that program.
• What’s “desirable”? One example is correctness. . .
The University of Sydney Page 18
Preconditions cannot be strengthened in the subtype
// precondition: input may be null or may not
Class A { public void doX(String input) {} }
// precondition: input must not be null
Class B extends A { public void doX(String input) {} }
B can no longer be used as an A
The University of Sydney Page 19
Postconditions cannot be weakened in the subtype
// postcondition: input is not modified
Class A { public void doX(List
// postcondition: input is only modified a little
Class B extends A { public void doX(List
input.add(“Just a tiny modification”);
}}
B can no longer be used as an A
The University of Sydney Page 20
Substitutability
• The aim is not to check if a replacement can do something the original couldn’t, but can
the replacement do everything the original could under the same circumstances.
• Substitutability is asking the question ‘Can one substitute one type for another with a
guarantee of no ill-effects? We might need to consider substitutability in cases:
• Refactoring
• Redesign
• Porting
• The context is ‘changing something in existing use’
The University of Sydney Page 24
SOLID: Interface Segregation
You should not be forced to implement
interfaces you don’t use!
The University of Sydney Page 25
SOLID: Dependency Inversion
No complex class should depend on simpler
classes it uses; they should be separated by
interfaces (abstract classes)
The details of classes should depend on the
abstraction (interface), not the other way
around
The University of Sydney Page 26
Summary of SOLID Principles
Single Responsibility: Every class should have a single responsibility and
that responsibility should be entirely met by that class;
Open/Closed: Open for extension but closed for modification; inheritance
is used for this, e.g., through the use of inherited abstract base classes;
Liskov Substitutability: If S<:T (“S is a subtype of T”) then a T object
can be replaced with an S object and no harm done;
Interface Segregation: Client code should not have to implement interfaces it
doesn’t need;
Dependency Inversion: High level, complex modules should not depend on
low-level, simple models — use abstraction, and implementation details should
depend on abstractions, not the other way around.
The University of Sydney Page 27
General Responsibility
Assignment Software
Pattern (GRASP)
Designing objects with responsibilities
The University of Sydney Page 28
Object Design
• “Identify requirements, create a domain model, add methods to the
software classes, define messages to meet requirements…”
• Too Simple!
• What methods belong where?
• How do we assign responsibilities to classes?
• The critical design tool for software development is a mind well educated in
design principles and patterns.
The University of Sydney Page 29
Responsibility Driven Design
– Responsibility is a contract or obligation of a class
– What must a class “know”? [knowing responsibility]
– Private encapsulated data
– Related objects
– Things it can derive or calculate
– What must a class “do”? [doing responsibility]
– Take action (create an object, do a calculation)
– Initiate action in other objects
– Control/coordinate actions in other objects
– Responsibilities are assigned to classes of objects during object design
The University of Sydney Page 30
Responsibilities: Examples
– “A Sale is responsible for creating SalesLineItems” (doing)
– “A Sale is responsible for knowing its total” (knowing)
– Knowing responsibilities are related to attributes, associations in the
domain model
– Doing responsibilities are implemented by means of methods.
The University of Sydney Page 31
Doing Responsibilities: Example
: A myB : B
doTwo
doOne
doThree
The University of Sydney Page 32
GRASP: Methodological Approach to OO Design
General Responsibility Assignment Software Patterns
The five basic principles:
• Creator
• Information Expert
• High Cohesion
• Low Coupling
• Controller
The University of Sydney Page 33
GRASP: Creator Principle
Problem
Who creates an A object
Solution
Assign class B the responsibility to create an instance of class A if one of these is true
B “contains” A
B “records” A
B “closely uses” A
B “has the Initialising data for” A
The University of Sydney Page 34
GRASP: Information Expert Principle
Problem
What is a general principle of assigning responsibilities to objects
Solution
Assign a responsibility to the class that has the information needed to fulfill it
: A myB : B
doTwo
doOne
doThree
The University of Sydney Page 35
Dependency
– A dependency exists between two elements if changes to the
definition of one element (the supplier) may cause changes to
the other (the client)
– Various reason for dependency
– Class send message to another
– One class has another as its data
– One class mention another as a parameter to an operation
– One class is a superclass or interface of another
The University of Sydney Page 36
When to show dependency?
– Be selective in describing dependency
– Many dependencies are already shown in other format
– Use dependency to depict global, parameter variable, local
variable and static-method.
– Use dependencies when you want to show how changes in one
element might alter other elements
The University of Sydney Page 37
Dependency: Parameter Variable
public class Sale{
public void updatePriceFor (ProductDescription description){
Money basePrice = description.getPrice();
//…
}
}
SalesLineItem
...
...
ProductDescription
...
...
1..*
lineItems
Sale
...
updatePriceFor( ProductDescription )
...
the Sale has parameter visibility to a
ProductDescription, and thus some kind of
dependency
The University of Sydney Page 38
Dependency: static method
public class Foo{
public void doX(){
System.runFinalization();
//..
}
}
System
...
runFinalization()
...
Foo
...
doX()
...
the doX method invokes the runFinalization
static method, and thus has a dependency on
the System class
The University of Sydney Page 39
Dependency labels
– There are many varieties of dependency, use keywords to differentiate them
– Different tools have different sets of supported dependency keywords.
– <
– <
– <
The University of Sydney Page 40
Coupling
– How strongly one element is connected to, has knowledge of, or
depends on other elements
– Illustrated as dependency relationship in UML class diagram
A
E
B
C
DF
The University of Sydney Page 41
GRASP: Low Coupling Principle
Problem
How to reduce the impact of change, to support low dependency, and increase reuse?
Solution
Assign a responsibility so that coupling remains low
The University of Sydney Page 42
Coupling – Example (NextGen POS)
We need to create a Payment instance and associate
it with the Sale.
What class should be responsible for this?
This assignment couple the Register class to
knowledge of the Payment class which increases
coupling
Payment RegisterSale
: Register p : Payment
:Sale
makePayment() 1: create()
2: addPayment(p)
Since Register record a payment in the
real-world domain, the Creator pattern
suggests register as a candidate for
creating the payment
The University of Sydney Page 43
Coupling – Example (NextGen POS)
From creator point of view, the previous design is
better.
In practice, consider the level of couple along
with other principles such as Expert and High
Cohesion
Better design from coupling point of view
It maintains overall lower coupling
: Register :Sale
:Payment
makePayment() 1: makePayment()
1.1. create()
The University of Sydney Page 44
Cohesion
– How strongly related and focused the responsibilities of an
element are
– Formal definition (calculation) of cohesion
– Cohesion of two methods is defined as the intersection of the sets of
instance variables that are used by the methods
– If an object has different methods performing different operations
on the same set of instance variables, the class is cohesive
The University of Sydney Page 45
High Cohesion
– Problem
– How to keep objects focused, understandable, and manageable,
and as a side effect, support Low Coupling?
– Solution
– Assign responsibilities so that cohesion remains high
The University of Sydney Page 46
Cohesion – Example (NextGen POS)
We need to create a (cash) Payment instance and associate it with the Sale.
What class should be responsible for this?
: Register : Sale
addPayment( p )
p : Payment
create()
makePayment()
Since Register record a payment in the
real-world domain, the Creator pattern
suggests register as a candidate for
creating the payment
Acceptable but could become incohesive as the
Register will increasingly need to carry out most
of the system operations assigned to it
e.g., Register responsible for doing the work of
20 operations (overburden)
The University of Sydney Page 47
Cohesion – Example (NextGen POS)
Better design from cohesion point of view
The payment creation responsibility is
delegated to the Sale instance
It supports high cohesion and low
coupling
: Register : Sale
makePayment()
: Payment
create()
makePayment()
The University of Sydney Page 48
Coupling and Cohesion
– Coupling describes the inter-objects relationship
– Cohesion describes the intra-object relationship
– Extreme case of “coupling”
– Only one class for the whole system
– No coupling at all
– Extremely low cohesion
– Extreme case of cohesion
– Separate even a single concept into several classes
– Very high cohesion
– Extremely high coupling
– Domain model helps to identify concepts
– OOD helps to assign responsibilities to proper concepts
The University of Sydney Page 49
Controller
– Problem
– What first object beyond the UI layer receives and coordinates
(“controls”) a system operation
– Solution
– Assign the responsibility to an object representing one of these
choices
• Represents the overall system, root object, device or subsystem
(a façade controller)
• Represents a use case scenario within which the system
operations occurs (a use case controller)
The University of Sydney Page 50
Controller
Which class of object should be responsible for receiving this
system event message?
It is sometimes called the controller or coordinator. It does not
normally do the work, but delegates it to other objects.
The controller is a kind of “facade” onto the domain layer from
the interface layer.
actionPerformed( actionEvent )
: ???
: Cashier
:SaleJFrame
presses button
enterItem(itemID, qty)
UI Layer
Domain
Layer
system operation message
Register
…
endSale()
enterItem()
makeNewSale()
makePayment()
makeNewReturn()
enterReturnItem()
. . .
System
endSale()
enterItem()
makeNewSale()
makePayment()
makeNewReturn()
enterReturnItem()
. . .
system operations
discovered during system
behavior analysis
allocation of system
operations during design,
using one facade controller
ProcessSale
Handler
…
endSale()
enterItem()
makeNewSale()
makePayment()
System
endSale()
enterItem()
makeNewSale()
makePayment()
enterReturnItem()
makeNewReturn()
. . .
allocation of system
operations during design,
using several use case
controllers
HandleReturns
Handler
…
enterReturnItem()
makeNewReturn()
. . .
The University of Sydney Page 1
Software Design and
Construction 1
SOFT2201 / COMP9201
Introduction to Design
Patterns
School of Computer Science
Dr. Martin McGrane
The University of Sydney Page 2
Copyright warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been reproduced and communicated to
you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the
Act ).
The material in this communication may be subject
to copyright under the Act. Any further copying or
communication of this material by you may be the
subject of copyright protection under
the Act.
Do not remove this notice.
The University of Sydney Page 3
Agenda
– Design Patterns
– GoF Design Patterns
– Creational Design Patterns
– Factory Method Pattern
– Builder Pattern
The University of Sydney Page 4
What is a Design Pattern?
The University of Sydney Page 5
Design Patterns
– A pattern is a description of a problem and its solution
– Tried and tested ideas for a recurring design problem
– Not a readily coded solution, but rather the solution path to a
common programming problem
– Design or implementation structure that achieves a particular
purpose
The University of Sydney Page 6
Essential Components of a Pattern
– The pattern name
– e.g., Factory Method
– The problem
– The pattern is designed to solve (i.e., when to apply the pattern)
– The solution
– The components of the design and how they related to each other
– Consequence
– The results and trade-offs of applying the pattern
– Advantages and disadvantages of using the pattern
The University of Sydney Page 7
Gang of Four Patterns (GoF)
• Official design pattern reference
• Famous and influential book about design patterns
• Recommended for students who wish to become
experts
• We will cover the most widely – used patterns
from the book
• 23 patterns in total – our unit will focus on 11
• GoF Design Patterns → Design Patterns as short
The University of Sydney Page 8
Design Patterns – Classification based on purpose
Scope Creational Structural Behavioural
Class Factory Method Adapter (class) Interpreter
Template Method
Object Abstract Factory
Builder
Prototype
Singleton
Adapter (object)
Bridge
Composite
Decorator
Façade
Flyweight
Proxy
Chain of Responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor
The University of Sydney Page 9
Design Patterns – Classification based on purpose
– Creational patterns
– Abstract the instantiation process
– Make a system independent of how its objects are created, composed
and represented
– Structural patterns
– How classes and objects are composed to form larger structures
– Behavioral patterns
– Concerns with algorithms and the assignment of responsibilities between
objects
The University of Sydney Page 10
Design Patterns – Classification based on relationships
– Patterns often used together
– E.g., Composite often used with Iterator or Visitor
– Alternative Patterns
– E.g., Prototype often alternative to Abstract Factory
– Patterns results in similar designs
– E.g., Structure diagram of Composite and Decorator are similar
The University of Sydney Page 11
Design Patterns – Classification based on relationships
Adapter
Bridge
Composite
Decorator
Façade
Proxy
Chain of
Reponsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
State Strategy
Template
Method
Visitor
Abstract
Factory
Builder
Factory
Method
Prototype
SingletonFlyweight
Structural
Pattern
Behavioural
Pattern
Creational
Pattern
avoiding
hysteresis
composed
using
saving state
of iteration
creating
composites
adding
responsibilities
to objects
iterating
children
defining
traversals
adding
operations
defining
the chain
sharing
states
sharing
strategies
complex
dependency
management
changing skin
vs internals defining
algorithm’s
steps
often
uses
implement
using
single
instance
single
instance
configure factory
dynamically
adding
operations
defining
grammar
* Adapted from the GoF book: Design Patterns
The University of Sydney Page 12
Selecting an Appropriate Design Pattern
It is useful to have some guidelines of how to select a pattern.
Some thoughts on how you might do that:
– Consider the ways in which the design patterns solve problems.
– We will go into details on this for several design patterns
– Decide on what the intent of each design is.
– Without knowing what the motivation of the design pattern is, it will be
hard to know whether it is right for you
– Look at the relationships among patterns
– It makes sense to use patterns that have a clear relationship, rather than
one that you have manufacture ad hoc
The University of Sydney Page 13
Selecting an Appropriate Design Pattern
– Consider patterns with similar purpose
– Creational, Structural and Behavioral are quite different purposes so
you should consider which one you need
– Look at why redesign might be necessary
– Knowing why a redesign might be needed will help you select the right
design to avoid having to redesign later
– What can vary?
– Your design should be open to variation where necessary
– Choose a design that will not lock you into a particular one, and enable
you to make variations without changing your design
The University of Sydney Page 14
Design Aspects Can be Varied by Design Patterns
Purpose Pattern Aspects that can change
Creational
Abstract Factory
Builder
Factory Method
Prototype
Singleton
Families of product objects
How a composite object gets created
Subclass of object that is instantiated
Class of object that is instantiated
The sole instance of a class
Structural
Adapter
Bridge
Composite
Decorator
Façade
Flyweight
Proxy
Interface to an object
Implementation of an object
Structure and composition of an object
Responsibilities of an object without subclassing
Interface to a subsystem
Storage costs of objects
How an object is accessed; its location
The University of Sydney Page 15
Design Aspects Can be Varied by Design Patterns
Purpose Pattern Aspects that can change
Behaviour
al
Chain of Responsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
State
Strategy
Template Method
Visitor
object that can fulfill a request
when and how a request is fulfilled
grammar and interpretation of a language
how an aggregate’s elements are accessed, traversed
how and which objects interact with each other
what private info. is stored outside an object, & when
number of objects that depend on another object; how the
dependent objects stay up to date
states of an object
an algorithm
steps of an algorithm
operations that can be applied to object(s) without changing
their class(es)
The University of Sydney Page 16
Creational Patterns
The University of Sydney Page 17
Creational Patterns
– Abstract the instantiation process
– Make a system independent of how its objects are created, composed and
represented
– Class creational patterns use inheritance to vary the class that’s instantiated
– Object creational pattern delegates instantiation to another object
– Provides flexibility in what gets created, who creates it, how it gets created
and when
The University of Sydney Page 18
Creational Patterns
Pattern Name Description
Abstract Factory Provide an interface for creating families of related or dependent objects
without specifying their concrete classes
Singleton Ensure a class only has one instance, and provide global point of access to it
Factory Method Define an interface for creating an object, but let sub-class decide which
class to instantiate (class instantiation deferred to subclasses)
Builder Separate the construction of a complex object from its representation so that
the same construction process can create different representations
Prototype Specify the kinds of objects to create using a prototype instance, and create
new objects by copying this prototype
The University of Sydney Page 19
Factory Method
Class Creational Pattern
An interface for creating an object
The University of Sydney Page 20
Factory Method Pattern
– Purpose/Intent
– Define an interface for creating an object, but let subclasses decide which class
to instantiate. Let a class defer instantiation to subclasses
– Also known as
– Virtual Constructor
– Motivated Scenario
– Suppose you have a general application framework (like Office) that
can create a variety of different applications and document types. To
create a spreadsheet applications, we might define SpreadsheetApp
and SpreadsheetDoc; for a word processing application we’d have
WordProcApp and WordProcDoc. Both use the common framework.
The University of Sydney Page 21
Factory Method Pattern
– Applicability
– A class cannot anticipate the class objects it must create
– A class wants its subclasses to specify the objects it creates
– Classes delegate responsibility to one of several helper subclasses, and
you want to localise the knowledge of which helper subclass is the
delegate
– Benefits
– Flexibility: subclasses get a hook for providing an extension to an
object; connects parallel class hierarchies
– Limitations
– Can require subclassing just to get an implementation
The University of Sydney Page 22
Factory Method Structure
The University of Sydney Page 23
Factory Method Participants
– Product
– Defines the interface of objects the factory method creates
– ConcreteProduct
– Implements the Product interface
– Creator
– Declares the factory method, which returns an object of type Product.
– ConcreteCreator
– Overrides the factory method to return an instance of the ConcreteProduct
The University of Sydney Page 24
Two varieties of Factory Method
– Variety 1: the Creator class is abstract
– This requires subclasses to be made because there is no reasonable
default value.
– On plus side, this avoids the problem of dealing with instantiating
unforeseeable classes
– Variety 2: the Creator class is concrete
– Creator may also define a default implementation of the factory
method that returns a default ConcreteProduct object
– This provides reasonable default behaviors, and enables subclasses to
override the default behaviors where required
The University of Sydney Page 25
Example
ShapeFactory sf = new RectangleFactory( );
Shape x = sf.createShape( );
The University of Sydney Page 26
Two varieties of Factory Method use
– Variety 1: only one Factory Method implementation is needed
– Existing code, such as a library, that is passed a Factory Method
implementation at runtime.
– Only one type of Product is needed for the lifetime of the client
– Variety 2: many Factory Method implementations are needed
– Many types of Products are needed at any time
– Something needs to select which type of Product to produce.
• Something needs to ‘store’ the Factory Method implementation
The University of Sydney Page 27
Selecting a Factory Method source
– ‘Simple Factory’
Product makeProduct(Identifier identifier) {
if (identifier.equals(…) {
return new ProductA();
} else if (identifier.equals(…) {
return new ProductB();
} else if …
}
The University of Sydney Page 28
Selecting a Factory Method source
– Factory Registry
– In essence, a mapping from identifier to implementation
private Map
public void registerFactory(Factory factory, Identifier identifier);
public Factory getFactory(Identifier identifier);
The University of Sydney Page 29
Builder
Object Creational Pattern
The University of Sydney Page 30
Builder
– Purpose/Intent
– Separate the construction of a complex object from its representation so
that the same construction process can create different representations
– Motivated Scenario
– You have a range of implementations that might expand, so must be
flexible, or you want to create instances of complex objects
– Applicability
– The algorithm for creating a complex object should be independent of
the parts that make up the object and how they’re assembled
– The construction process must allow different representations for the
object that’s constructed
The University of Sydney Page 31
Builder
– Benefits
– Gives flexibility that can be extended by implementing new subclasses
of the Builder, and isolates code of construction from implementation
– Limitations
– Not completely generic, less useful in situations where variety of
implementations is not high
The University of Sydney Page 32
Builder — Structure
The University of Sydney Page 33
Builder – Participants
– Builder
– Specifies an abstract interface for creating parts of a Product object
– ConcreteBuilder
– Constructs and assembles parts of the product by implementing the
Builder interface
– Defines and keeps track of the representation it creates.
– Provides an interface (GetResult) for retrieving the product
The University of Sydney Page 34
Builder – Participants
– Director
– Constructs an object using the Builder interface
– Product
– Represents the complex object under construction.
– ConcreteBuilder builds the product’s internal representation and defines the process
by which it’s assembled
– Includes classes that define the constituent parts, including interfaces for assembling
the parts into the final result
The University of Sydney Page 35
Builder – Rich Text Format Example
– A reader for the RTF (Rich Text Form) document exchange e format should
be able to convert RTF to many text formats
– Problem: the number of possible conversions is open-ended, so it should be
easy to add a new conversion without modifying the reader
– A solution is to configure the RTFReader class with a TextConverter object
that converts RTF to another textual representation
– Subclasses of TextConverter specialise in different conversions and formats
– Each kind of converter class takes the mechanism for creating and
assembling a complex object and puts it behind an abstract interface
The University of Sydney Page 36
Builder – Rich Text Format Example
The University of Sydney Page 37
Builder – Rich Text Format Example
– Builder Pattern captures all the relationships
– Each converter class is called a builder in the pattern, and the reader is
called the director
– It separates the algorithm for interpreting a textual format from how a
converted format gets created and represented
– The RTFReader’s parsing algorithm can be reused to create different
text representations from RTFdocuments – just configure the RTFReader
with different subclasses of TextConverter
The University of Sydney Page 38
Builder – Collaboration
Director d = new Director( );
Builder b = new ConcreteBuilder1( );
d.construct(b);
Product p = b.GetResult( );
The University of Sydney Page 39
Builder – Consequences (1)
– Varying product’s internal representation
– Because the product is constructed through an abstract interface, all you need to
do to change the product’s internal representation is define a new kind of
builder
– Isolation of code construction and representation
– Each ConcreteBuilder contains all the code to create and assemble a particular
kind of product.
– Different Directors can reuse it to build Product variants from the same set of
parts
• E.g., SGMLReader uses the same TextConverters to generate different
formats (ASCIIText, TextWidget and TexXText)
The University of Sydney Page 40
Builder – Consequences (2)
– Finer control over the construction process
– The builder pattern constructs the product step by step under the director’s
control
– Only when the product finished does the director retrieve it from the builder
– The builder interface reflects the process of constructing the product more than
other creational patterns
The University of Sydney Page 41
Java Builder
– Related to, but not the same as GoF Builder
– Avoids issues with multiple complex constructors
– Provides default values for parameters of a complex object
– Parameters may be changed as needed
– A build() method creates the object – now only one constructor is needed
The University of Sydney Page 42
References
– Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
1995. Design Patterns: Elements of Reusable Object-Oriented Software.
Addison-Wesley Longman Publishing Co., Inc., Boston, MA, USA.
– Craig Larman. 2004. Applying UML and Patterns: An Introduction to Object-
Oriented Analysis and Design and Iterative Development (3rd Edition).
Prentice Hall PTR, Upper Saddle River, NJ, USA.
The University of Sydney Page 1
Software Design and
Construction 1
SOFT2201 / COMP9201
Behavioural Design Patterns
School of Computer Science
Dr. Martin McGrane
The University of Sydney Page 2
Copyright warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been reproduced and communicated to
you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the
Act ).
The material in this communication may be subject
to copyright under the Act. Any further copying or
communication of this material by you may be the
subject of copyright protection under
the Act.
Do not remove this notice.
The University of Sydney Page 3
Agenda
– Behavioural Design Patterns
– Strategy
– State
The University of Sydney Page 4
Behavioural Design
Patterns
The University of Sydney Page 5
Behavioural Patterns
– Concerned with algorithms and the assignment of responsibilities between objects
– Describe patterns of objects and class, and communication between them
– Simplify complex control flow that’s difficult to follow at run-time
– Concentrate on the ways objects are interconnected
– Behavioural Class Patterns (SOFT3202)
– Use inheritance to distribute behaviour between classes (algorithms and computation)
– Behavioural Object Patterns
– Use object composition, rather than inheritance. E.g., describing how group of peer objects
cooperate to perform a task that no single object can carry out by itself
– Question: how peer objects know about each other?
The University of Sydney Page 6
Behavioural Patterns (GoF)
Pattern Name Description
Strategy Define a family of algorithms, encapsulate each one, and make them interchangeable (let
algorithm vary independently from clients that use it)
Observer Define a one-to-many dependency between objects so that when one object changes, all its
dependents are notified and updated automatically
Memento Without violating encapsulation, capture and externalise an object’s internal state so that the
object can be restored to this state later
Command Encapsulate a request as an object, thereby letting you parameterise clients with different
requests, queue or log requests, and support undoable operations
State Allow an object to alter its behaviour when its internal state changes. The object will
appear to change to its class
Visitor Represent an operation to be performed on the elements of an object structure. Visitor lets you
define a new operation without changing the classes of the elements on which it operates
Other patterns Interpreter, Iterator, Mediator, Chain of Responsibility, Template Method
The University of Sydney Page 7
Strategy Design Pattern
Object Behavioural Pattern
Algorithm design through encapsulation
The University of Sydney Page 8
Strategy Design Pattern
– Purpose/Intent
– Define a family of algorithms, encapsulate each one, and make them
interchangeable
– Let the algorithm vary independently from clients that use it
– Known as
– Policy
– Motivation Scenario
– Design for varying but related algorithms that are suitable for different contexts
• Ability to change these algorithms
The University of Sydney Page 9
Strategy – Applicability
– Many related classes differ only in their behaviour
– You need different variant of an algorithm
– An algorithm uses data that should be hidden from its clients
– A class defines many behaviours that appear as multiple statements in its
operations
The University of Sydney Page 10
Strategy – Example (Text Viewer)
– Many algorithms for breaking a stream of text into lines
– Problem: hard-wiring all such algorithms into the classes that require them
– More complex and harder to maintain clients (more line breaking algorithms)
– Not all algorithms will be needed at all times
The University of Sydney Page 11
Strategy – Structure
ContextInterface()
Context
Algorithm()
Strategy
Algorithm()
ConcreteStrategyA
Algorithm()
ConcreteStrategyB
Algorithm()
ConcreteStrategyC
strategy
The University of Sydney Page 12
Strategy – Example (Text Viewer)
Maintain &
update the line
breaks of text
Different line breaking algorithms (strategies)
Composition perspective:
private compositor com;
public composition (compositor c) {
com = c;}
public void Repair ( ) { com.compose();}
Client perspective:
composition com = new composition(new SimpleCompositor( ));
com.Repair( );
The University of Sydney Page 13
Strategy – Participants
Participant Goals
Strategy (Compositor) Declares an interface common to all supported algorithms
Used by context to call the algorithm defined by
ConcereteStrategy
ConcereteStrategy
(SimpleCompositor,
TeXCompositor, etc)
Implements the algorithm using the Strategy interface
Context (Composition) Is configured with a ConcreteStrategy object
Maintains a reference to a Strategy object
May define an interface that lets Strategy access its data
The University of Sydney Page 14
Strategy – Collaborations
– Strategy and Context interact to implement the chosen algorithm
– A context may pass all data required by the algorithm to the Strategy
– The context can pass itself as an argument to Strategy operations
– A context forwards requests from its clients to its strategy
– Clients usually create and pass a ConcreteStrategy object to the context;
thereafter, clients interact with the context exclusively
The University of Sydney Page 15
Strategy – Consequences (Benefits)
– Family of related algorithms (behaviours) for context to reuse
– Alternative to sub-classing
– Why not sub-class a Context class directly to give it different behaviours?
– Strategies eliminate conditional statements
– Provide choice of different implementation of the same behavior
The University of Sydney Page 16
Strategy – Consequences (Drawbacks)
– Clients must be aware of different strategies
– Understand how strategies differ
– Communicate overhead between Strategy and Context
– Strategy interface is shared by all ConcreteStrategy classes whether the
algorithms they implement are trivial or complex
– Increased number of objects in an application
– Can be reduced by implementing strategies as stateless objects that context can
share
– Strategy objects often make good flyweight (sharing strategies)
The University of Sydney Page 17
Strategy – NextGen PoS System
– Design problem: how to provide more complex pricing logic, e.g., store-
wide discount for the day, senior citizen discounts
– The pricing strategy (or policy) for a sale can vary:
– 10% of all sales during a specific period
– $10 off if the total sale is greater than $200
– Other variations
– How do we design our system to accommodate such varying pricing
policies?
The University of Sydney Page 18
NextGen PoS – Pricing
Strategy Classes
PercentDiscount
PricingStrategy
percentage : float
getTotal( s:Sale ) :
Money
AbsoluteDiscount
OverThreshold
PricingStrategy
discount : Money
threshold : Money
getTotal( s:Sale ) :
Money
«interface»
ISalePricingStrategy
getTotal( Sale ) : Money
{
return s.getPreDiscountTotal() * percentage
}
???
PricingStrategy
…
…
{
pdt := s.getPreDiscountTotal()
if ( pdt < threshold ) return pdt else return pdt - discount } The University of Sydney Page 19 Strategy Pattern – NextGen PoS System – Create multiple SalesePricingStrategy classes, each with a polymorphic getTotal method – Each getTotal method takes the Sale object as a parameter – The pricing strategy object can find the pre-discount price from the Sale, and they apply the discounting policy – The implementation of each getTotal method will be different – E.g., PercentDiscountPricingStrategy will discount by a percentage The University of Sydney Page 20 PoS System – Strategy POS Collaboration :PercentDiscount PricingStrategy s : Sale st = getSubtotal t = getTotal lineItems[ i ] : SalesLineItem t = getTotal( s ) pdt = getPreDiscountTotal { t = pdt * percentage } note that the Sale s is passed to the Strategy so that it has parameter visibility to it for further collaboration loop The University of Sydney Page 21 PoS System – Strategy POS Collaboration – A strategy is attached to the Sale object (context object) – The Sale object delegates some of the work to its strategy object – The message to the context and strategy objects is not required to be the same (e.g., getTotal) – The Sale object passes a reference to itself on to the strategy object The University of Sydney Page 22 State Design Pattern Object Behavioural Pattern Taking control of objects from the inside A structured way to control the internal behaviour of an object The University of Sydney Page 23 State Design Pattern – Purpose/Intent – Allow an object to change its behaviour when its internal state changes – The object will “appear to change its class” when the state changes – The object can transition between various behaviours depending on the state – Known as – Objects for States – Motivating Scenario – We can use subtypes of classes with different functionality to represent different states, such as for a TCP connection with Established, Listening, Closed as states The University of Sydney Page 24 Motivating Scenario – TCP network connection – States: Established, Listening and Closed – TCP connection responds based on its current state The University of Sydney Page 25 State Design Pattern – Applicability – Any time you need to change behaviours dynamically, i.e., the state of an object drives its behaviour and change its behaviour dynamically at run-time – There are multi-part checks of an object’s state to determine its behaviour, i.e., operations have large, multipart conditional statements that depend on the object’s state – Benefits – Removes case or if/else statements depending on state, and replaces them with function calls; makes the state transitions explicit; permits states to be shared – Limitations – Does require that all the states have to have their own objects The University of Sydney Page 26 State Pattern – Structure Request() Context state->Handle()
Handle()
State
Handle()
ConcreteStateA
Handle()
ConcreteStateB
The University of Sydney Page 27
Motivating Scenario
– TCP network connection
– States: Established, Listening and Closed
– TCP connection responds based on its current state
Context State
Concrete States
handle()
The University of Sydney Page 28
State Pattern – Participants
– Context (TCPConnection)
– Defines the interface of interest to clients
– Maintains an instance of a ConcreteState subclass that defines the current state
– State (TCPState)
– Defines an interface for encapsulating the behaviour associated with a certain state of the
Context
– ConcreteState subclasses (TCPEstablished, TCPListen, TCPClosed)
– Each subclass implements a behaviour associated with a state of the Context
The University of Sydney Page 29
State Pattern – Collaborations
– Context delegates state – specific requests to the current ConcreteState
object
– A context may pass itself as an argument to the State object handling the
request, so the State object access the context if necessary
– Context is the primary interface for clients
– Clients can configure a context with State objects, so its clients don’t have to deal with the
State objects directly
– Either Context or the ConcreteState subclasses can decide which state
succeeds another and under what circumstances
The University of Sydney Page 30
State Pattern – Code Example
The University of Sydney Page 31
State Pattern – Code Example
The University of Sydney Page 32
State Pattern – Code Example
– What is the output of StateDemo?
The University of Sydney Page 33
State Pattern – Consequences
– Localises state-specific behaviour for different states
– Using data values and context operations make code maintenance difficult
– State distribution across different subclasses useful when there are many states
– Better code structure for state-specific code (better than monolithic)
– It makes state transition explicit
– State transitions as variable assignments
– State objects can protect the context from inconsistent state
– State objects can be shared
– When the state they represent is encoded entirely in their type
The University of Sydney Page 34
State Pattern – Implementation (1)
– Defining the state transitions
– Let the state subclasses specify their successor state to make the transition (decentralised)
– Achieves flexibility – easy to modify and extend the logic
– Introduces implementation dependencies between subclasses
– Table-based state transitions
– Look-up table that maps every possible input to a succeeding state
– Easy to modify (transition data not the program code) but:
• Less efficient than a functional call
• Harder to understand the logic (transition criteria is less explicit)
• Difficult to add actions to accompany the state transitions
The University of Sydney Page 35
State Pattern – Implementation (2)
– When to create and destroy state objects?
– Pre-create them and never destroy them
• Useful for frequent state changes (save costs of re-creating states)
• Context must keep reference to all states
– Only when they are needed and destroyed them thereafter
• States are not known at run-time and context change states frequently
The University of Sydney Page 36
State Pattern – Implementation (3)
– Using dynamic inheritance
– Changing the object’s class at run-time is not possible in most OO
languages
– delegation-based languages allow changing the delegation target at
run-time
The University of Sydney Page 37
References
– Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
1995. Design Patterns: Elements of Reusable Object-Oriented Software.
Addison-Wesley Longman Publishing Co., Inc., Boston, MA, USA.
The University of Sydney Page 1
Software Design and
Construction 1
SOFT2201 / COMP9201
Testing
School of Computer Science
Dr. Martin McGrane
The University of Sydney Page 2
Copyright warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been reproduced and communicated to
you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the
Act ).
The material in this communication may be subject
to copyright under the Act. Any further copying or
communication of this material by you may be the
subject of copyright protection under
the Act.
Do not remove this notice.
The University of Sydney Page 3
Agenda
– Software Testing
– Unit Testing
The University of Sydney Page 4
Software Engineering Body of Knowledge
– Software Requirements
– Software Design / Modelling
– Software Construction
– Software Testing
– Software Maintenance
– Software Configuration Management
– Software Engineering Process
– Software Engineering Tools and Methods
– Software Quality
Software Engineering Body of Knowledge (SWEBOK) https://www.computer.org/web/swebok/
The University of Sydney Page 5
Why Software Testing?
The University of Sydney Page 6
Software is Everywhere!
• Societies, businesses and governments depend on SW
• Power, Telecommunication, Education, Government, Transport, Finance, Health
• Work automation, communication, control of complex systems
• Large software economies in developed countries
• IT application development expenditure in the US more than $250bn/year1
• Total value added GDP in the US2: $1.07 trillion
• Emerging challenges
• Security, robustness, human user-interface, and new computational platforms
1 Chaos Report, Standish group Report, 2014
2 softwareimpact.bsa.org
The University of Sydney Page 7
Software Failure – Ariane 5 Disaster5
– What happened?
• European large rocket – 10 years development, ~$7 billion
• Unmanaged software exception resulted from a data conversion from 64-
bit floating point to a 16-bit signed integer
• Backup processor failed straight after using the same software
• Exploded 37 seconds after lift-off
– Why did it happen?
• Design error, incorrect analysis of changing requirements, inadequate
validation and verification, testing and reviews, ineffective development
processes and management
5 http://iansommerville.com/software-engineering-book/files/2014/07/Bashar-Ariane5.pdf
http://iansommerville.com/software-engineering-book/files/2014/07/Bashar-Ariane5.pdf
The University of Sydney Page 8
Why Software Testing?
– Software development and maintenance costs
• Financial burden of failure
– Total costs of imperfect software testing for the US in 2002 was AUD86 billion*
– One third of the cost could be eliminated by ‘easily’ improved software testing
– Need to develop functional, robust and reliable software
– Human/social factor
• Dependence on software in many aspects of their lives
– Small software errors can lead to disasters
The University of Sydney Page 9
What is Software
Testing?
The University of Sydney Page 10
Software testing
– Software process to
⚫ demonstrate that software meets its requirements (validation testing)
⚫ Find incorrect or undesired behaviour caused by defects (defect testing)
⚫ e.g. crashes, incorrect results, data corruption
– Part of the software Verification and Validation (V&V) process
The University of Sydney Page 11
Types of testing
– Unit testing
⚫ Verify functionality of software components independent of the whole system
– Integration testing
⚫ Verify interactions between software components
– System Testing
⚫ Verify functionality and behaviour of the entire software system
⚫ Includes security, performance, reliability, and external interfaces
– Acceptance testing
⚫ Verify desired acceptance criteria are met from the users point of view
The University of Sydney Page 12
Software Verification and Validation
– Software testing is part of software V&V
– The goal of V&V is to establish confidence that the software is “fit for purpose”
– Software Validation
⚫ Are we building the right product?
⚫ Ensures that the software meets customer expectations
– Software Verification
⚫ Are we building the product correctly
⚫ Ensure the software meets the stated functional and non-functional requirements
The University of Sydney Page 13
Black box or White box
– Black box testing
⚫ The internals of the software system is unknown
⚫ Only inputs to the system are controlled, and outputs from the system are measured
⚫ Specification-based testing
⚫ May be the only choice to test libraries without access to internal
– White box testing
⚫ The internals of the software system are known
⚫ The internal structure is tested directly
⚫ Unit, integration, system testing
The University of Sydney Page 14
Types of testing
Functional testing
⚫ Unit
⚫ Integration
⚫ System
⚫ Regression
⚫ Interface
⚫ User Acceptance
⚫ Configuration
⚫ Sanity
Non-functional testing
⚫ Performance
⚫ Stress
⚫ Reliability
⚫ Usability
⚫ Load
⚫ Security
The University of Sydney Page 15
Who should design and
run tests?
The University of Sydney Page 16
Test engineer
– Independent testers
– Independent testers do not have the same biases as the developer
– Different assumptions
– Domain specific knowledge of testing
– Developer
– Understands the system being developed
– Domain specific knowledge of the system
– Cheaper
– Can finish writing the system faster without tests since they won’t make mistakes
The University of Sydney Page 17
Unit Testing
The University of Sydney Page 18
Unit testing
– The process of verifying functionality of software components
independently
⚫ Unit can mean methods, functions, or object classes
⚫ Verify that each unit behaves as expected
⚫ Carried out by developers and software testers
⚫ First level of testing
The University of Sydney Page 19
Why unit testing
– Maintain and change code at a smaller scale
– Discover defects early and fix it when its cheaper
– Simplify integration testing
– Simplify debugging
– Code reusability
The University of Sydney Page 20
How to do the unit test
– Identify the unit that you want to test
– Design test case
– Prepare test data (input and expected output)
– Run test case using test data
– Compare result to expected output
– Prepare test reports
The University of Sydney Page 21
Designing test cases
– Effective test cases show:
⚫ The unit does what it is supposed to do
⚫ Reveal defects, if they exist (does not do what it is not supposed to do)
– Design two types of test case
⚫ Test normal operation of the unit
⚫ Test abnormal operation (common problems)
The University of Sydney Page 22
Designing test cases – techniques
– Partition testing (equivalence partitioning)
⚫ Identify groups of tests that have common characteristics
⚫ From each group, choose specific tests
⚫ Use program specifications, documentation, and experience
– Guideline-based testing
⚫ Use testing guidelines based on previous experience of the kinds of errors made
⚫ Depends on the existence of previous experience (developer/product)
The University of Sydney Page 23
Equivalence partitioning
– Groups of test input that have common characteristics
⚫ Positive numbers
⚫ Negative numbers
⚫ Boundaries
– Program is expected to behave in a comparable way for all members of a group
⚫ Control flow should be similar for all members
– Choose test cases from each partition
The University of Sydney Page 24
Test case selection
– Understanding developers thinking
⚫ Easy to focus on typical values of input
⚫ Common case, and what was asked for
⚫ Easy to overlook a typical value of input
⚫ Users, other developers, new features, all have different expectations
– Choose test cases that are
⚫ On boundaries of partitions
⚫ In ‘midpoint’ of partitions
⚫ NB: Boundaries may be unclear (-1, 0, 1, 0.5)
The University of Sydney Page 25
Test cases – identifying partitions
– Consider this specification:
⚫ The program accepts 4 to 8 inputs that are five digit integers greater than 10,000
– Identify the input partitions and possible test inputs
?
The University of Sydney Page 26
Test cases – identifying partitions
– Consider this specification:
⚫ The program accepts 4 to 8 inputs that are five digit integers greater than 10,000
– Identify the input partitions and possible test inputs
– How many values
⚫ <4, 4-8, >8
– How many digits
⚫ < 5, 5, > 5, non-digits
– How big
⚫ > 10000
⚫ etc.
The University of Sydney Page 27
Test case selection guidelines
– Knowledge of types of test case effective for finding errors
– If testing sequences, arrays, lists:
⚫ Single value
⚫ Different sequences of different sizes
⚫ Test partition boundaries (first, middle, last)
⚫ Consider order of values
The University of Sydney Page 28
Test case selection guidelines
– Choose inputs that force the system to generate all expected
error messages
– Design inputs that cause buffer overflows
– Repeat input
– Force invalid outputs to be generated
– Force computation results that are too large or too small
– Domain specific knowledge!
The University of Sydney Page 29
Acquiring domain specific knowledge
– Be an expert on the system, or type of system
– or,
– Make many mistakes
– Identify mistakes
– Write tests to identify mistakes
– Fix mistakes
– Be an expert on the system, or type of system
– Regression testing!
The University of Sydney Page 30
Regression testing
– If a defect is identified in software it can be fixed
⚫ How did it get there?
⚫ How do you stop it happening again?
The University of Sydney Page 31
Regression testing
– Regression: a defect that has been fixed before, happens again
⚫ Human error
⚫ Version control problems
⚫ Specific case is fixed, but the general case remains
⚫ Convergent evolution
The University of Sydney Page 32
Regression testing
– As defects in software are fixed, tests are written that demonstrate that the software
is fixed (at least in regard to that particular defect)
⚫ Tests can be re-run with each change in the software system
⚫ Regression testing
⚫ Frequently automated
The University of Sydney Page 33
When to test
The University of Sydney Page 34
When to test
– Continuously
– When the software system changes
⚫ Code changes
⚫ Design changes
⚫ Infrastructure changes
⚫ At regular intervals in case the above missed a change
The University of Sydney Page 35
How to test
The University of Sydney Page 36
How to test
– Write testable code
public static void main(String[] args) {
// All the code
// All
}
The University of Sydney Page 37
How to test
– Write testable code
public static void main(String[] args) {
Application app = new Application();
}
Public class Application {
Application() {
// All the code
}
}
The University of Sydney Page 38
How to test
– Write testable code
public static void main(String[] args) {
Application app = new Application();
app.doEverything();
}
public class Application {
Application() {
// Construct the application
}
public void doEverything() {
// All the code
}
}
The University of Sydney Page 39
How to test
– Write testable code
public class Application {
Application() {
// Construct the application
}
public void doEverything() {
// Most of the code
doSomeOfTheThings();
}
public void doSomeOfTheThings() {
// Some of the code
}
}
The University of Sydney Page 40
How to test
public class Application {
Application() {
// Construct the application
}
public void doEverything() {
// Some code
Thing = doSomeOfTheThings(thing);
// More code
}
public BigThing doSomeOfTheThings(LittleThing littleThing) {
// Some of the code that deals with LittleThings
}
}
The University of Sydney Page 41
How to test
public class Application {
// …
public void doEverything(LittleThingFactory littleThingFactory) {
LittleThing firstThing= littleThingFactory.makeThing();
LitteThing secondThing = doStuff(firstThing);
doStuff(secondThing);
doStuffWithTwoThings(firstThing, secondThing);
doSomeOfTheThings(thing);
// …
}
protected BigThing doSomeOfTheThings(LittleThing littleThing) {
// Some of the code that deals with LittleThings
}
// …
}
The University of Sydney Page 42
Unit Testing in Java
The University of Sydney Page 43
Unit testing terminology
– Unit test
⚫ A piece of code written by a developer that executes a specific functionality in the
code under test and asserts a certain behaviour or state as correct
⚫ Small unit of code (method/class)
⚫ External dependencies are removed
⚫ (Mocking)
– Test fixture
⚫ Testing context
⚫ Shared test data
⚫ Methods for setting up test data
The University of Sydney Page 44
Unit testing frameworks for Java
– JUnit
– TestNG
– Jtest
– Many others
– Custom, developer-written, tests
The University of Sydney Page 45
JUnit
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import mypackage.Calculator;
class CalculatorTest {
@Test
void addition() {
Calculator calculator = new Calculator();
assertEquals(2, calculator.add(1, 1));
}
}
The University of Sydney Page 46
JUnit
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import mypackage.Calculator;
class CalculatorTest {
@Test
void addition() {
Calculator calculator = new Calculator();
assertEquals(2, calculator.add(1, 1));
}
}
The University of Sydney Page 47
JUnit
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import mypackage.Calculator;
class CalculatorTest {
@Test
void addition() {
Calculator calculator = new Calculator();
assertEquals(2, calculator.add(1, 1));
}
}
The University of Sydney Page 48
JUnit
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import mypackage.Calculator;
class CalculatorTest {
@Test
void addition() {
Calculator calculator = new Calculator();
assertEquals(2, calculator.add(1, 1));
}
}
The University of Sydney Page 49
JUnit
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import mypackage.Calculator;
class CalculatorTest {
@Test
void addition() {
Calculator calculator = new Calculator();
int expected = 2;
assertEquals(expected, calculator.add(1, 1));
}
}
The University of Sydney Page 50
JUnit
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import mypackage.Calculator;
class CalculatorTest {
@Test
void addition() {
Calculator calculator = new Calculator();
int expected = 2;
int actual = calculator.add(1, 1);
assertEquals(expected, actual);
}
}
The University of Sydney Page 51
JUnit
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import mypackage.Calculator;
class CalculatorTest {
@Test
void addition() {
Calculator calculator = new Calculator();
int expected = 2;
int actual = calculator.add(1, 1);
assertEquals(expected, actual);
}
}
The University of Sydney Page 52
JUnit constructs
– JUnit test
⚫ A method only used for testing
– Test suite
⚫ A set of test classes to be executed together
– Test annotations
⚫ Define test methods (e.g., @Test, @Before)
⚫ JUnit uses the annotations to build the tests
– Assertion methods
⚫ Check expected result is the actual result
⚫ e.g., assertEquals, assertTrue, assertSame
The University of Sydney Page 53
JUnit annotations
– @Test
⚫ Identifies a test method
– @Before/@BeforeEach
⚫ Execute before each test
– @After/@AfterEach
⚫ Execute after each test
– @BeforeClass/@BeforeAll
⚫ Execute once, before all tests in this class
– @AfterClass/@AfterAll
⚫ Execute once, after all tests in this class
The University of Sydney Page 54
JUnit assertions
– assertEquals(expected, actual)
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import mypackage.Calculator;
class CalculatorTest {
@Test
void addition() {
Calculator calculator = new Calculator();
int expected = 2;
int actual = calculator.add(1, 1);
assertEquals(expected, actual);
}
}
The University of Sydney Page 55
JUnit assertions
– assertEquals(message, expected, actual)
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import mypackage.Calculator;
class CalculatorTest {
@Test
void addition() {
Calculator calculator = new Calculator();
int expected = 2;
int actual = calculator.add(1, 1);
assertEquals(“Expected value != actual”, expected, actual);
}
}
The University of Sydney Page 56
JUnit assertions
– assertTrue
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import mypackage.Calculator;
class CalculatorTest {
@Test
void addition() {
Calculator calculator = new Calculator();
assertTrue(2 == calculator.add(1, 1));
}
}
The University of Sydney Page 57
JUnit assertions
– assertTrue
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import mypackage.Calculator;
class CalculatorTest {
@Test
void addition() {
Calculator calculator = new Calculator();
assertTrue(“Can’t do 1 + 1 :(“, 2 == calculator.add(1, 1));
}
}
The University of Sydney Page 58
JUnit assertions
import …
class CalculatorTest {
Calculator calculator
@Before
void setup() {
calculator = new Calculator();
}
@Test
void additionBothPositive() {
assertEquals(2, calculator.add(1, 1));
assertEquals(5, calculator.add(4, 1));
assertEquals(5, calculator.add(2, 3));
}
…
The University of Sydney Page 59
What are we going to learn next week?
– Mid semester break
– Followed by Monday public holiday
– No lecture \o/
– Tutorials are not affected by the public holiday
– for the rest of the semester, tutorials are in the same week as the relevant lecture
The University of Sydney Page 1
SOFT2201/COMP9201:
Software Design and
Construction 1
Code Reviews
Dr Martin McGrane
School of Computer Science
The University of Sydney Page 2
Outline
– Why review
– What to review
– What is a review
– What is a formal review
– What is an informal review
The University of Sydney Page 3
Why review?
The University of Sydney Page 4
Why review?
– What is the software, or aspect of the software, to be
reviewed for?
– What are the specifications that need to be met?
– Does the software, or aspect thereof, being reviewed,
meet those specifications?
The University of Sydney Page 5
What is the software for and does it work?
– What is the software, or aspect of the software, to be
reviewed for?
– What are the specifications that need to be met?
– Does the software, or aspect thereof, being reviewed,
meet those specifications?
– We need a way to check that the software is
appropriately designed to meet the expected criteria
The University of Sydney Page 6
What to review?
The University of Sydney Page 7
What to review?
– Any part of a software project can be reviewed
– Code
– Documentation
– Processes
– Management
– Specifications
– Planning
The University of Sydney Page 8
What is a review?
The University of Sydney Page 9
What is a review?
– A software review is
“A process or meeting during which a software
product, set of software products, or a software process
is presented to project personnel, managers, users,
customers, user representatives, auditors or other
interested parties for examination, comment or approval.”
IEEE Standard 1028-2008, “IEEE Standard for Software Reviews”, clause 3.5
The University of Sydney Page 10
Formal vs
informal
reviews
The University of Sydney Page 11
What is a
formal review?
The University of Sydney Page 12
Fagan inspection
– An early effort to formalise the process of reviews
– The basis, or at least similar, to subsequent formal
approaches
– Describe program development process in terms of
operations
– Define ‘entry’ and ‘exit’ criteria for all operation
– Specify objectives for the inspection process to keep
the team focused on one objective at a time
The University of Sydney Page 13
Fagan inspection
– Classify errors by type, rank by frequency, identify
which types to spend most time looking for
– Analyse results and use for constant process
improvement
The University of Sydney Page 14
Fagan inspection operation
– Specify objectives for the inspection process to keep
the team focused on one objective at a time
– Planning
– Overview
– Preparation
– Inspection
– Rework
– Follow-up
The University of Sydney Page 15
Fagan inspection operations
– Planning
– Preparation of materials
– Arranging of participants
– Arranging of meeting place
– Overview
– Group education of participants on review materials
– Assignment of roles
The University of Sydney Page 16
Fagan inspection operations
– Preparation
– Participants review item to be inspected and supporting
material to prepare for the meeting, noting any questions or
possible defects
– Participants prepare their roles
– Inspection meeting
– Actual finding of defect
The University of Sydney Page 17
Fagan inspection operations
– Rework
– Rework is the step in software inspection in which the defects
found during the inspection meeting are resolved by the
author, designer or programmer. On the basis of the list of
defects the low-level document is corrected until the
requirements in the high-level document are met.
– Follow-up
– In the follow-up phase of software inspections all defects found
in the inspection meeting should be corrected. The moderator
is responsible for verifying that this is indeed the case. They
should verify that all defects are fixed and no new defects are
inserted while trying to fix the initial defects.
The University of Sydney Page 18
Formal inspection
– Management review
– Monitor progress
– Determine status of plans
– Evaluate management effectiveness
– Supports decisions about changes in direction, resource
allocation, and scope
The University of Sydney Page 19
Formal inspection
– Management review
– Maintenance plans
– Disaster recovery
– Migration strategies
– Customer complaints
– Risk management plans
– …
The University of Sydney Page 20
Formal inspection
– Management review roles
– Decision maker
– Review leader
– Recorder
– Management staff
– Technical staff
The University of Sydney Page 21
Formal inspection
– Management review processes
– Preparation
– Plan time and resources
– Provide funding
– Provide training
– Ensure reviews are conducted
– Act on reviews
The University of Sydney Page 22
Formal inspection
– Technical review
– Software requirements
– Software design
– Software test documentation
– Specifications
– … procedures
The University of Sydney Page 23
Formal inspection
– Technical review roles
– Decision maker
– Review leader
– Recorder
– Technical reviewer
The University of Sydney Page 24
Formal inspection
– Inspections
– The purpose of an inspection is to detect and identify software
product anomalies. An inspection is a systematic peer
examination that does one or more of the following:
• Verifies that the software product satisfies its specifications
• Verifies that the software product exhibits specified quality
attributes
• Verifies that the software product conforms to applicable
regulations, standards, guidelines, plans, specifications,
and procedures
The University of Sydney Page 25
External Audits
– Reviews may also be performed by external groups
– A formal process is generally highly desirable when dealing
with external groups and may extend any of the above
approaches
The University of Sydney Page 26
What is an
informal review?
The University of Sydney Page 27
Informal reviews
– Reviews may be far less formal
– Pair-programming
– “Over the shoulder”
– Walkthroughs
– Presentations
– Self-guided reviews
– Checklists
– Ongoing informal reviews may easily be as thorough
as a formal review, overall
The University of Sydney Page 28
Informal reviews
– Formal reviews are far more effective than informal
reviews
– Informal reviews are far more convenient than formal
reviews
The University of Sydney Page 29
How about a
semi-formal
code review?
The University of Sydney Page 30
Purpose
– Have a clear purpose for the review
– Identify all relevant project specifications
– Identify how the specifications can be verified
– Identify who the relevant stakeholders are
The University of Sydney Page 31
Change List/Pull Request reviews
– A complete, ‘working’ project exists
– A set of changes are to be applied
– The changes must be reviewed before they are
accepted
The University of Sydney Page 32
Change List/Pull Request reviews
The University of Sydney Page 33
Change List/Pull Request reviews
The University of Sydney Page 34
Change List/Pull Request reviewers
– Owner
– Is this change wanted?
– Technical reviewer
– Does this change work? (specialised knowledge)
– Technical reviewer
– Is this change maintainable? (general knowledge)
• (Can I understand it?)
The University of Sydney Page 35
A brief visit to Design by Contract (DbC)
– A software design approach for program correctness
– Also known as contract programming, programming by
contract, design-by-contract programming
– Definition of formal, precise and verifiable interface
specification for software components
– Pre-conditions, postconditions and invariants (contract)
The University of Sydney Page 36
Reviewing DbC change lists
– Definition of formal, precise and verifiable interface
specification for software components
– Pre-conditions, postconditions and invariants (contract)
– Are the pre-conditions met?
– Are the post-conditions met?
– Are the invariants invariant?
– Are these likely to stay so?
– How hard is it to verify?
The University of Sydney Page 37
Reviewing DbC change lists
– How do the changes relate to the contract?
– Documentation of the change
– How do you verify this?
– Reviewer selection
– Documentation of project
– Project processes
• testing
The University of Sydney Page 38
Change List/Pull Request reviews
– Owner
– Does the documentation agree with the specifications?
– Technical reviewer
– Are there tests?
– Do the tests verify the pre/post conditions are met?
– Technical reviewer
– Is the code written according to the style guide?
– Does the code use appropriate design patterns?
The University of Sydney Page 39
Change List review challenges
– Size
– The more there is to read, the more scope there is to miss
problems
– Many small code reviews are more manageable (somewhat
like unit tests vs blackbox system tests)
– A large code review can take so much time that special
planning is needed
– May need to place limits on acceptable sizes for review
The University of Sydney Page 40
Change List review challenges
– Scope
– Changes that affect many processes may need more
reviewers for the required technical knowledge
– May sometimes be helped by multiple, smaller changelists
– May bring specifications from different processes into conflict,
requiring management review
• May also be triggered by small changes with big impacts,
such as changing JDK version
The University of Sydney Page 41
Change List review challenges
– Complexity
– Fast, efficient, code may be hard to read and hard to
understand
– Is the code complexity, thus review complexity and
maintenance complexity, worth the improvement?
– Does the complexity affect maintainability and testability?
The University of Sydney Page 42
Change List review challenges
– Confusion
– What is the change meant to be for?
– May be doing too many unrelated things
– May be making unnecessary changes
– May even be about a disagreement between colleagues (my
approach is better!)
The University of Sydney Page 43
Change List review challenges
The University of Sydney Page 44
Change List review challenges
The University of Sydney Page 45
Change List review challenges
– ‘Fix sound’
– Changes look reasonable
– Should it be removed
completely?
– Who decides?
The University of Sydney Page 46
Change List review challenges
– ‘Fix sound’
– Changes may be good
changes, but they’re not
related to sound any more.
The University of Sydney Page 47
Change List review techniques
– Formalise the review process
– All changes must be reviewed
– We already have review roles – Owner, Readability, Technical
– The planning and preparation are only needed once per
project (plus for each major change in direction)
– The project needs clear specifications, requirements, and
sufficient documentation
– The CL must meet the requirements
– Changes are recommended and either acted on or disagreed
with and the result re-evaluated
The University of Sydney Page 48
Change List review comments
– Be clear
– Be objective
– State the issue
– State what is needed to fix it
– E.g., “Document this method”
– E.g., “These braces aren’t needed, please remove”
– E.g., “Resubmit this PR as two separate PRs”
– E.g., “Use informative variable names”
The University of Sydney Page 49
Change List review examples
– This needs tests
– This needs unit tests
– This needs integration tests
– This needs documentation
– What is this for?
– This doesn’t follow the style guide
– Resubmit without the temp files
The University of Sydney Page 50
Change List review techniques
– Automation is great!
– When it works
– Code style
– Coverage
– Test suites
– Performance tests
– Spelling (A little more challenging in code)
– Common code issues
The University of Sydney Page 51
Reviewing larger projects
– You may need to review complete, larger projects,
rather than small changes.
– A formal review process will ensure all parties
understand what is expected
– The code inspection will be similar to a changelist
review, but with no existing base to compare to
– More work is needed to verify requirements
The University of Sydney Page 52
Change List review comments
– E.g., “Document this method”
– E.g., “These braces aren’t needed, please remove”
– E.g., “Split this file into one per class, for readability”
– E.g., “Use informative variable names”
– A report on a set of changes would discuss why the
comments were made, the benefits, the problems, and
discuss other approaches
– A code review is far more concise and directed
The University of Sydney Page 53
References
– Fagan, M. E. (1976). “Design and code inspections to
reduce errors in program development”. IBM Systems
Journal. 15 (3): 182–211. doi:10.1147/sj.153.0182
– IEEE Std . 1028-1997, “IEEE Standard for Software
Reviews“, doi:10.1109/IEEESTD.2008.4601584
https://doi.org/10.1007%2F978-3-642-48354-7_14
https://doi.org/10.1109/IEEESTD.2008.4601584
The University of Sydney Page 1
Software Design and
Construction 1
SOFT2201 / COMP9201
Adapter and Observer
School of Computer Science
Dr. Martin McGrane
The University of Sydney Page 2
Copyright warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been reproduced and communicated to
you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the
Act ).
The material in this communication may be subject
to copyright under the Act. Any further copying or
communication of this material by you may be the
subject of copyright protection under
the Act.
Do not remove this notice.
The University of Sydney Page 3
Agenda
– Structural Design Pattern
– Adapter
– Behavioural Design Pattern
– Observer
The University of Sydney Page 4
Structural Design Patterns
The University of Sydney Page 5
Structural Design Patterns
– How classes and objects are composed to form larger structures
– Structural class patterns use inheritance to compose interfaces
or implementations
– Structural object patterns describe ways to compose objects to
realise new functionality
– The flexibility of object composition comes from the ability to change the
composition at run-time
The University of Sydney Page 6
Structural Patterns (GoF)
Pattern Name Description
Adapter Allow classes of incompatible interfaces to work together. Convert the
interface of a class into another interface that clients expect.
Façade Provides a unified interface to a set of interfaces in a subsystem. Defines a
higher-level interface that makes the subsystem easier to use.
Decorator Attach additional responsibilities to an object dynamically (flexible alternative to
subclassing for extending functionality)
Composite Compose objects into tree structures to represent part-whole hierarchies. It lets
clients treat individual objects and compositions of objects uniformly
Flyweight Use sharing to support large numbers of fine-grained objects efficiently.
Bridge Decouple an abstraction from its implementation so that the two can vary
independently
Proxy Provide a placeholder for another object to control access to it
The University of Sydney Page 7
Adapter Pattern
Class, Object Structural
The University of Sydney Page 8
Adapter
– Intent
– Convert the interface of a class into another interface that clients
expect.
– Lets classes work together that couldn’t otherwise because of
incompatible interfaces.
– Known as
– Wrapper
– Motivation
– Sometimes existing code that has the functionality we want doesn’t have
the right interface we want to use
The University of Sydney Page 9
Adapter
– Applicability
– To use an existing class with an interface does not match the one you need
– You want to create a reusable class that cooperates with unrelated or
unforeseen classes, i.e., classes that don’t necessarily have compatible interfaces
– (Object adapter only) Adapt an existing interface, which has several existing
implementations.
– Benefits
– Code reuse
The University of Sydney Page 10
Class Adapter – Structure
• Request multiple inheritance to adapt the Adaptee to Target, supported by C++
The University of Sydney Page 11
Object Adapter – Structure
The University of Sydney Page 12
Adapter – Participants
– Target
– Defines the domain-specific interface that Client uses
– Client
– Collaborates with objects conforming to the Target interface.
– Adaptee
– Defines an existing interface that needs adapting.
– Adapter
– Adapts the interface of Adaptee to the Target interface
– Collaborations
– Clients call operations on an Adapter instance. In turn, the Adapter calls Adaptee
operations that carry out the request
The University of Sydney Page 13
Class Adapter – Consequences
– When we want to adapt a class and all its subclasses, a class adapter won’t
work
– It adapts Adaptee to Target by committing to a concrete Adaptee class
– Lets Adapter override some of Adaptee’s behavior, since Adapter is a
subclass of Adaptee
– Introduces only one object, and no additional pointer indirection is needed to
get to the Adaptee (for programming language such as C++)
The University of Sydney Page 14
Object Adapter – Consequences
– Lets a single Adapter work with many Adaptees – i.e., the Adaptee itself
and all of its subclasses (if any).
– Makes it harder to override Adaptee behavior. It will require sub-classing
Adaptee and making Adapter refer to the subclass rather than the Adaptee
itself
The University of Sydney Page 15
Adapter Example — Problem
+setLocation()
+getLocation()
+display()
+fill()
+setColor()
+undisplay()
Shape
+display()
+fill()
+undisplay()
Line
+display()
+fill()
+undisplay()
Square
+setLocation()
+getLocation()
+displayit()
+fillit()
+setItsColor()
+undisplayIt()
XXCircle
The University of Sydney Page 16
Adapter Example — Solution
+setLocation()
+getLocation()
+display()
+fill()
+setColor()
+undisplay()
Shape
+display()
+fill()
+undisplay()
Line
+display()
+fill()
+undisplay()
Square
+setLocation()
+getLocation()
+displayit()
+fillit()
+setItsColor()
+undisplayIt()
XXCircle
+getlocation()
+setLocation()
+display()
+fill()
+setColor()
+undisplay()
Circle
1 1
class Circle extends Shape{
…
private XXCircle myXXCircle;
..
public Circle(){
myXXCircle = new XXCircle();
}
void public display(){
myXXcircle.displayIt();
}
…
}
The University of Sydney Page 17
Adapter pattern: general structure
– Target (Shape)
– defines the domain-specific interface that
Client uses.
– Adapter (Circle)
– adapts the interface Adaptee to the
Target interface.
– Adaptee (XXCircle)
– defines an existing interface that needs
adapting.
– Client (ShapeApp)
– collaborates with objects conforming to the
Target interface.
The University of Sydney Page 18
Different Implementations of Adapter
+display()
+fill()
+undisplay()
Line
+display()
+fill()
+undisplay()
Square
+setLocation()
+getLocation()
+displayit()
+fillit()
+setItsColor()
+undisplayIt()
XXCircle
+getlocation()
+setLocation()
+display()
+fill()
+setColor()
+undisplay()
Circle
class Circle implements Shape extends XXCircle{
…
..
public Circle( double radius){
super( radius);
}
void public display(){
super.displayIt();
}
…
}
+display()
+fill()
+undisplay()
«interface»
Shape
The University of Sydney Page 19
Object Adapter and Class Adapter
– Object Adapter
– Relies on object composition to achieve adapter
– Class Adapter
– Relies on class inheritance to achieve adapter
The University of Sydney Page 20
Two Reuse Mechanisms
– Inheritance and Delegation
– Inheritance: reuse by subclassing;
• “is-a” relationship (white-box reuse)
– Delegation: reuse by composition;
• “has-a” relationship (black-box reuse)
• A class is said to delegate another class if it implements an operation by resending a
message to another class
– Rule of thumb – design principles #1
– Favour object composition over class inheritance
The University of Sydney Page 21
Inheritance Approach
import java.util.Hashtable;
class AddressBook extends Hashtable{
String put(String name, String address){
return (String) super.put (name,
address);
}
// Problem with the inheritance approach
public static void main(String[] argv){
AddressBook contact = new
AddressBook();
contact.put (“SOFT2201”, new
Exception());
}
}
+put(in key : object, in element : object) : object
+get(in key : object) : object
+containsKey(in key : object) : bool
+containsValue(in element : object) : bool
Hashtable
+put(in name : string, in address : string) : string
AddressBook
The University of Sydney Page 22
Delegation Approach
class AddressBook{
private Hashtable
AddressBook(){
table = new Hashtable();
}
String put(String name, String address){
return table.put (name, address);
}
…
}
+put(in name : string, in address : string) : string
Addressbook
+put(in key : object, in element : object) : object
+get(in key : object) : object
+containsKey(in key : object) : bool
+containsValue(in element : object) : bool
Hashtable
1
1
The University of Sydney Page 23
Inheritance vs. Delegation
– Benefits of delegation
– Extensibility: we can change the internal representation of
AddressBook to another class
– Subtyping: AddressBook can not be substituted for a Hashtable in
any of the client code.
The University of Sydney Page 24
Observer Pattern
Object Behavioural
The University of Sydney Page 25
Observer
– Intent
– Define a one-to-many dependency between objects so that when one object
changes state, all its dependents are notified and updated automatically
– Known as
– Dependents, Publish-Subscribe
– Motivation:
– A collection of cooperating classes (consistency between related objects)
– Consistency while maintaining loosely-coupled, and highly reusable classes
The University of Sydney Page 26
Observer – Applicability
– An abstraction has two aspects, one dependent on the other
– A change to one object requires changing others, and it’s not clear how many objects
need to be changed
– An object should be able to notify other objects without making assumptions about
who these objects are
The University of Sydney Page 27
Observer – Publish-Subscribe
– Problem
– You need to notify a varying list of objects that an event has occurred
– Solution
– Subscriber/listener interface
– Publisher: dynamically register interested subscribers and notify them
when an event occurs
The University of Sydney Page 28
Observer – Example (Data Representation)
The University of Sydney Page 29
Observer – Structure
The University of Sydney Page 30
Observer – Participants
Participant Goals
Subject Knows its observers. Any number of observer objects may observe a subject.
Provides an interface for attaching and detaching observer objects
Observer Defines an updating interface for objects that should be notified of changes
in a subject
ConcreteSubject Stores state of interest to ConcreteObserver objects
Sends notifications to its observers when its state changes
ConcreteObserver Maintains a reference to a ConcreteSubject object
Stores state that should stay consistent with the subject’s.
Implements the observer’s updating interface to keep its state consistent
The University of Sydney Page 31
Observer – Collaborations
The University of Sydney Page 32
Observer – Consequences
– Abstract coupling between Subject and Observer
– Subject only knows its Observers through the abstract Observer class (it doesn’t know the
concrete class of any observer)
– Support for broadcast communication
– Notifications are broadcast automatically to all interested objects that subscribe to the
Subject
– Add/remove Observers anytime
– Unexpected updates
– Observers have no knowledge of each other’s presence, so they can be blind to the cost
of changing the subject
– An innocent operation on the subject may cause a cascade of updates to Observers and
their dependents
The University of Sydney Page 33
Observer In GUI Class Library
– Observer pattern is the basic structure of event handling system in Java’s
GUI library
– Each GUI widget is a publisher of GUI related events
– ActionEvent, MouseClickedEvent, ListSelectionEvent,…
– Observer can be any other objects (GUI or non-GUI objects)
The University of Sydney Page 34
Observer in Java GUI
– Example
– A simple GUI with a JTextField and a JList component
– Each time the List is selected, the selected text is displayed in the
JTextField.
– JList supports ListSelectionListener
– A subclass of JTextField should implements
ListSelectionListener
The University of Sydney Page 35
Observer in Java GUI
The University of Sydney Page 36
QuickEntryApplication
The University of Sydney Page 37
Publisher-Many-Subscribers
– One publisher instance could have zero to many registered subscribers
– E.g., one instance of an AlarmClock could have three registered alarm windows, four
Beepers, and on ReliabilityWatchDog
– When an alarm even happens, all eight of these AlarmListeners are notified via an
onAlarmEvent
– Observer Implementation (Java)
– Events are communicated via a regular message, such as on onPropertyEvent
– Event is more formally defined as a class, and filled with appropriate event data
– The event is then passed as a parameter in the event message
The University of Sydney Page 38
Publisher-Many-
Subscribers
«interface»
AlarmListener
onAlarmEvent( source, time )
Beeper
onAlarmEvent( source, time )
…
{
display notification dialog
box
}
AlarmClock
addAlarmnListener( AlarmListener lis )
publishAlarmEvent( time )
setTime( newTime )
…
*
alarmListeners
{
time = newTime;
if ( time == alarmTime )
publishAlarmEvent( time );
}
{
alarmListeners.add( lis );
}
{
for each AlarmListener al in alarmListeners
al.onAlarmEvent( this, time );
}
AlarmWindow
onAlarmEvent( source, time )
…
javax.swing.JFrame
…
setTitle()
setVisible()
…
ReliabilityWatchDog
onAlarmEvent( source, time )
…
{
beep
}
{
check that all required processes
are executing normally
}
The University of Sydney Page 39
References
– Craig Larman. 2004. Applying UML and Patterns: An Introduction to Object-
Oriented Analysis and Design and Iterative Development (3rd Edition).
Prentice Hall PTR, Upper Saddle River, NJ, USA.
– Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
1995. Design Patterns: Elements of Reusable Object-Oriented Software.
Addison-Wesley Longman Publishing Co., Inc., Boston, MA, USA.
The University of Sydney Page 1
SOFT2201/COMP9201:
Software Design and
Construction 1
Memento and Prototype
Dr. Martin McGrane
School of Computer Science
The University of Sydney Page 2
Copyright warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been reproduced and communicated to
you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the
Act ).
The material in this communication may be subject
to copyright under the Act. Any further copying or
communication of this material by you may be the
subject of copyright protection under
the Act.
Do not remove this notice.
The University of Sydney Page 3
Agenda
– Behavioural Design Pattern
– Memento
– Creational Design Pattern
– Prototype
The University of Sydney Page 4
Memento Design Pattern
Object Behavioural
The University of Sydney Page 5
Behavioural Patterns (GoF)
Pattern Name Description
Strategy Define a family of algorithms, encapsulate each one, and make them interchangeable (let
algorithm vary independently from clients that use it)
State Allow an object to alter its behaviour when its internal state changes. The object will appear to
change to its class
Observer Define a one-to-many dependency between objects so that when one object changes, all its
dependents are notified and updated automatically
Memento Without violating encapsulation, capture and externalise an object’s internal state so that
the state can later be restored to this state
The University of Sydney Page 6
Memento Pattern
– Intent
– Capture and externalise an object’s internal state so that the object can
be restored to this state later, without violating encapsulation
– Applicability
– A snapshot of an object’s, or some portion of an object’s, state must be saved so
that it can be restored to that state later, and
– A direct interface to obtaining the state would expose implementation details
and break the object’s encapsulation
The University of Sydney Page 7
Memento Pattern
– Intent
– Capture and externalise an object’s internal state so that the object can
be restored to this state later, without violating encapsulation
– Examples
– Save/Load
– Undo/Redo
The University of Sydney Page 8
Memento – Implementing Undo
– Consider implementing checkpoints and an undo mechanism that lets users
revert operations
– How could such behaviour be designed?
– What information should be captured?
– How and where should the information be stored?
– Is the way you proposed to store the information a good design? Why? Why
not?
The University of Sydney Page 9
Memento – Implementing Undo
– State information must be stored so that objects can be restored to their
previous state
– Encapsulation – objects normally encapsulate some or all of their state which
makes it inaccessible to other objects and impossible to save externally
– Exposing this state would violate encapsulation; and can compromise
application’s reliability and extensibility
The University of Sydney Page 10
Memento – Graphics Editor (Undo)
– A graphics editor allow users to connect and move shapes
– E.g., connect two rectangles with a line
– Rectangles stay connected when the user moves either of the rectangles
– The editor ensures that the line stretches to maintain the connection
The University of Sydney Page 11
Memento – Graphics Editor (Undo) – Problem
– ConstraintSolver object records connections as they are made and generates
mathematical equations that describe them
– ConstraintSolver uses the results of its calculation to rearrange the
graphics so that they maintain the proper connections
– How to “undo” a move operation?
– Store the original distance moved and move the object back to an equivalent
distance
The University of Sydney Page 12
Memento – Graphics Editor (Undo) – Problem
– Does the ConstraintSolver’s public interface suffice to allow precise reversal
of its effect on other objects?
– The undo mechanism must work closely with the ConstraintSolver to re-
establish the previous state
– Should avoid exposing the ContraintSolver’s internals to the undo
mechanism
– How to solve this problem?
The University of Sydney Page 13
Memento – Graphics Editor (Undo) – Solution
– The undo mechanism requests a memento from the originator when it needs
to checkpoint the originator’s state
– The originator initialise the memento with current state information
– Only the originator can store and retrieve information from memento – the
memento is not transparent to other objects
The University of Sydney Page 14
Memento – Graphics Editor (Undo) – Solution
1. When a user makes a move operation, the editor requests a memento from
the ConstraintSolver
2. The ConstraintSolver creates and returns a memento, an instance of a class
(e.g., SolverState), which contains data structures that describe the current
state of the ConstraintSolver’s internal equations and variables
3. When the user undoes the move operation, the editor gives the SolverState
back to the ConstraintSolver
4. The ConstraintSolver changes its internal structures to return its equations
and variables to their exact previous state
The University of Sydney Page 15
Memento – Structure
The University of Sydney Page 16
Memento – Structure
ConstraintSolver
SolverState state SolverState
The University of Sydney Page 17
Memento – Participants (1)
– Memento (SolverState)
– Stores internal state of the Originator object. The memento may store as much or
as little of the originator’s internal state as necessary at its originator’s discretion
– Protects against access by objects other than the originator. Mementos have
effectively two interfaces
• Caretaker: sees a narrow interface to the Memento — it can only pass the
memento to other objects
• Originator: sees a wide interface, one that lets it access all the data
necessary to restore itself to its previous state
The University of Sydney Page 18
Memento – Participants (2)
– Originator (ConstraintSolver)
– Creates a memento containing a snapshot of its current internal state
– Uses the memento restore its internal state
– Caretaker (undo mechanism)
– Responsible for the memento’s safekeeping
– Never operates on or examines the contents of a memento
The University of Sydney Page 19
Memento – Collaborations
The University of Sydney Page 20
Memento – Consequences (1)
– Preserve encapsulation boundaries
– By protecting other objects from potentially complex originator internals
– Simplifies Originator
– Originator keeps the versions of internal state that clients have requested
– Might be expensive
– If the originator must copy large amounts of information to store in the memento
or,
– If clients often create and return mementos to the originator
The University of Sydney Page 21
Memento – Load/Save
Text document editor
‒ We want to save the state so we can load it again later
‒ The Originator contains the state that represents the document being edited (and
perhaps the interface to the editing functionality.)
The University of Sydney Page 22
Memento – Load/Save
Text document editor
‒ We want to save the state so we can load it again later
‒ The Originator contains the state that represents the document being edited (and
perhaps the interface to the editing functionality.)
‒ Should the Originator need to know how to save the state, or where to save it to?
‒ Is tight coupling between Originator and storage of state a good idea?
‒ Will it help if we need to change the implementation of saving later?
‒ Should the Originator need to know when it is necessary to save or load the
state?
‒ (Hint – no to all)
The University of Sydney Page 23
Memento – Load/Save
Text document editor
‒ We want to save the state so we can load it again later
‒ The Originator contains the state that represents the document being edited
‒ A Memento stores the state, and has an interface that gives an Originator full access
to the state (for restoring purposes).
‒ Should the Memento need to know how to save the state, or where to save it to?
‒ Is tight coupling between Memento and storage of state a good idea?
‒ Will it help if we need to change the implementation of saving later?
‒ Should the Memento need to know when it is necessary to save or load the state?
‒ (Hint – no to all)
The University of Sydney Page 24
Memento – Load/Save
Text document editor
‒ We want to save the state so we can load it again later
‒ The Originator contains the state that represents the document being edited
‒ A Memento stores the state, and has an interface that gives an Originator full access
to the state (for restoring purposes).
‒ If a Caretaker needs to store a state, it asks the Originator for a Memento
representing the current state, then stores it.
‒ If a Caretaker needs to restore a state, it asks the Originator to restore state, and
passes it a Memento containing the state.
The University of Sydney Page 25
Memento – Load/Save
Text document editor state
‒ We want to save the state so we can load it again later
‒ What is the state?
‒ Complete copy of the current document
‒ All steps needed to turn start document into current document
‒ Difference from previous stored state
‒ The command used to change previous state to current state
‒ All reasonable choices in different circumstances
The University of Sydney Page 26
Memento – Load/Save
Text document editor
‒ Originator
‒ Knows what the state is and how to use it
‒ Memento
‒ Knows of state, but only needs to store it and restrict access
‒ Caretaker
‒ Knows how to store state, and how to get/set it from the Originator.
The University of Sydney Page 27
Prototype Design Pattern
Object Creational
The University of Sydney Page 28
Creational Patterns (GoF)
Pattern Name Description
Factory Method Define an interface for creating an object, but let sub-class decide which class to
instantiate (class instantiation deferred to subclasses)
Builder Separate the construction of a complex object from its representation so that the same
construction process can create different representations
Prototype Specify the kinds of objects to create using a prototype instance, and create new
objects by copying this prototype
Singleton Ensure a class only has one instance, and provide global point of access to it
The University of Sydney Page 29
Prototype
– Intent
– Specify the kinds of objects to create using a prototypical instance, and
create new objects by copying this prototype
– Applicability
– When a system should be independent of how its products are created,
composed, and represented
– To avoid building a class hierarchy of factories that parallels the class
hierarchy of products
– When instances of a class can have one of only a few different
combinations of state
– When the classes to instantiate are specified at run-time
The University of Sydney Page 30
Prototype
– Intent
– Specify the kinds of objects to create using a prototypical instance, and
create new objects by copying this prototype
– Applicability
– When a system should be independent of how its products are created,
composed, and represented
– To avoid building a class hierarchy of factories that parallels the class
hierarchy of products
– When instances of a class can have one of only a few different
combinations of state
– When the classes to instantiate are specified at run-time
The University of Sydney Page 31
Prototype
– A simple example
public interface Entity {}
// various classes that implement Entity
…
AbstractCollection
– How do you make a deep copy of your container?
The University of Sydney Page 32
Prototype – Structure
The University of Sydney Page 33
Prototype – Participants
– Prototype
– Declares an interface for cloning itself
– ConcretePrototype
– Implements an operation for cloning itself.
– Client
– Creates a new object by asking a prototype to clone itself
– Collaborations
– A client asks a prototype to clone itself
The University of Sydney Page 34
Prototype – Consequences (1)
– It hides the concrete product classes from the client, thereby reducing the
number of names clients know about
– These patterns let a client work with application-specific classes without
modification
– Each subclass of prototype must implement the clone operation
The University of Sydney Page 35
Prototype – Consequences (1)
– It hides the concrete product classes from the client, thereby reducing the
number of names clients know about
– These patterns let a client work with application-specific classes without
modification
– Each subclass of prototype must implement the clone operation
The University of Sydney Page 36
Prototype – Consequences (2)
1- Adding and removing products at run-time
– New concrete product class can be incorporated into a system
– The client can install and remove prototypes at run-time
2- Specifying new objects by varying values
– New kinds of objects can be defined by instantiating existing classes and
registering the instances as prototypes of client objects
– A client can exhibit new behaviour by delegating responsibility to the
prototype – this kind of design lets users define new “classes” without
programming (cloning a prototype is similar to instantiating a class)
The University of Sydney Page 37
Prototype – Consequences (3)
1- Specifying new objects by varying structure ( ~Builder)
– Many applications build objects from parts and subparts and for
convenience let you instantiate complex, user-defined structures
– Editors for circuit designs build circuits out of sub-circuits; specific sub-circuits can be used
– Similarly, sub-circuit can be added as a prototype to the palette of
available circuit elements
– When the composite circuit object implements clone as a deep copy, circuits with different
structures can be prototype
The University of Sydney Page 38
Prototype – Consequences (4)
4- Reduced sub-classing
– By cloning prototype instead of asking factory method to make a new
object
– Factory method produces a hierarchy of Creator classes that parallel the class
hierarchy
The University of Sydney Page 39
Prototype – Consequences (4)
4- Reduced sub-classing
– By cloning prototype instead of asking factory method to make a new
object
public class NotQuiteAFactoryMethodButSortaIs {
private MyPrototypeInterface prototype;
public NotQuiteAFactoryMethodButSortaIs(
MyPrototypeInterface prototype) {
this.prototype = prototype;
}
public MyPrototypeInterface create() {
return prototype.clone();
}
}
The University of Sydney Page 40
Prototype – Consequences (5)
5- Configure an application with classes dynamically
An application that wants to create instances of a dynamically loaded class
won’t be able to reference its constructor statically – how to do this?
– The run-time environment creates an instance of each class automatically
when it’s loaded, and it registers the instance with a prototype manager
– Then the application can ask the prototype manager for instances of newly
loaded classes, classes that weren’t linked with the program originally
The University of Sydney Page 41
Prototype – Implementation (1)
Using a prototype manager
– Keep a registry (prototype manager) of available prototypes when prototypes
in a system can be created and destroyed dynamically
– Clients will store and retrieve prototypes from the register, but will not manage them
– Before cloning, a client will ask the register for a prototype
– Prototype manager has operations for registering a prototype under a key and unregistering
it
– Clients can change or even browse the registry at run-time
The University of Sydney Page 42
Prototype – Implementation (2)
Implementing the clone operation
– Shallow copy vs deep copy
– Does cloning an object in turn clone its instance variables or do the clone and
original just share the variables
– Cloning with complex structures usually requires a deep copy because the clone
and the original must be independent
– Ensure the clone’s component are clones of the prototype’s components
The University of Sydney Page 43
Prototype – Implementation (3)
Initialising clones
– Some clients may want to initialise some or all of its internal state to values of
their choice
– Can’t pass these values in the Clone operation, as their number will vary between classes of
prototypes
– Clients may use already defined operations in your prototype classes for re-setting key
values/states
– You may need to introduce such initialise operations that set clone’s internal state accordingly
• Be aware of the deep copying clone operations
The University of Sydney Page 44
Prototype – Object.clone()
Java provides a clone() method
– Is it helpful?
Creates and returns a copy of this object. The precise meaning of “copy” may depend
on the class of the object. The general intent is that, for any object x, the expression:
x.clone() != x
will be true, and that the expression:
x.clone().getClass() == x.getClass()
will be true, but these are not absolute requirements. While it is typically the case that:
x.clone().equals(x)
will be true, this is not an absolute requirement.
The University of Sydney Page 45
Prototype – Object.clone()
Java provides a clone() method
– Is it helpful?
“Creates and returns a copy of this object. The precise meaning of “copy” may depend on the
class of the object. The general intent is that, for any object x, the expression:
…”
Ambiguous and restrictive
Deep or shallow?
Use only if you have read the api documentation, understand the limitations, and are sure the
rest of the related code will behave properly.
The University of Sydney Page 46
Prototype – MyClass.copy()
Write your own clone() method
– Is it helpful?
− The definition of shallow or deep is project dependent
− Use is project dependent
− If the method is public, document its use well
The University of Sydney Page 47
Prototype – MyClass.copy()
Write your own clone() method using a copy constructor
public class MyClass {
// fields
public MyClass(MyClass original) {
// copy all fields from original to this
}
/** Clear and well written documentation */
public MyClass copy() {
return new MyClass(this);
}
}
The University of Sydney Page 48
Prototype – MyInterface.copy()
Write your own clone() method using a copy constructor
public interface MyInterface {
/** Clear and well written documentation */
public MyInterface copy();
}
public class MyClass implements MyInterface {
public MyClass copy() {
// …
}
}
The University of Sydney Page 49
Prototype – MyInterface.copy()
Write your own clone() method using a copy constructor
public class MyClass {
/** Clear and well written documentation */
public MyClass copy() { … }
}
public class MyOtherClass extends MyClass {
}
The University of Sydney Page 50
Prototype – MyInterface.copy()
Write your own clone() method using a copy constructor
public class MyClass {
/** Clear and well written documentation */
public MyClass copy() { … }
}
public class MyOtherClass extends MyClass {
public MyOtherClass copy() {
// …
}
}
Don’t forget your
children
The University of Sydney Page 51
Prototype
– A simple example, and a simple solution
public interface Entity {public Entity copy();}
// various classes that implement Entity
…
AbstractCollection
– How do you make a deep copy of your container?
– for (Entity entity : entities) { newContainer.add(entity.copy(); }
The University of Sydney Page 52
Prototype
– A simple example, and a slightly less simple solution
public interface Entity {public Entity copy();}
public class MyEntityContainer {
public MyEntityContainer copy();
}
…
MyEntityContainer entities;
– How do you make a deep copy of your ccontainer?
– … newEntities = entities.copy();
– (Don’t forget the children)
The University of Sydney Page 53
References
– Craig Larman. 2004. Applying UML and Patterns: An Introduction to Object-
Oriented Analysis and Design and Iterative Development (3rd Edition).
Prentice Hall PTR, Upper Saddle River, NJ, USA.
– Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
1995. Design Patterns: Elements of Reusable Object-Oriented Software.
Addison-Wesley Longman Publishing Co., Inc., Boston, MA, USA.
The University of Sydney Page 1
SOFT2201/COMP9201:
Software Design and
Construction 1
Singleton, Decorator, and
Façade
Dr Martin McGrane
School of Computer Science
The University of Sydney Page 2
Copyright warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been reproduced and communicated to
you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the
Act ).
The material in this communication may be subject
to copyright under the Act. Any further copying or
communication of this material by you may be the
subject of copyright protection under
the Act.
Do not remove this notice.
The University of Sydney Page 3
Agenda
– Creational Design Pattern
– Singleton
– Structural Design Pattern
– Decorator and Façade
The University of Sydney Page 4
Singleton Pattern
Object Creational
The University of Sydney Page 5
Creational Patterns (GoF)
Pattern Name Description
Factory Method Define an interface for creating an object, but let sub-class decide which class to
instantiate (class instantiation deferred to subclasses)
Builder Separate the construction of a complex object from its representation so that the same
construction process can create different representations
Prototype Specify the kinds of objects to create using a prototype instance, and create new
objects by copying this prototype
Singleton Ensure a class only has one instance, and provide a global point of access to it
The University of Sydney Page 6
Singleton
– Intent
– Ensure a class only has one instance, and provide a global point
of access to it
– Motivation
– Make the class itself responsible for keeping track of its sole
instance (intercept requests to create new objects and provide a
way to access its instance)
– There can be many printers in a system, but there should be only
one printer queue
The University of Sydney Page 7
Singleton
– Applicability
– There must be exactly one instance of a class, and it must be
accessible to clients from a well-known access point
– The sole instance should be extensible by subclassing, and
clients should be able to use an extended instance without
modifying their code
– Structure
The University of Sydney Page 8
Singleton
– Participants
– Singleton defines an instance() operation that lets clients access
its unique instance. instance() is a class operation
– May be responsible for creating its own unique instance
– Collaboration
– Clients access a Singleton instance solely through Singleton’s
instance() operation.
The University of Sydney Page 9
Singleton Implementation
public class Singleton {
private static Singleton instance = null;
// Private constructor to prevent direct
initialisation.
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class Client {
…
Singleton single = Singleton.getInstance();
}
The University of Sydney Page 10
Singleton Example
public class ConfigurationReader {
private static ConfigurationReader instance = null;
private ConfigurationReader() { }
public static ConfigurationReader getInstance() {
if (instance == null) {
instance = new ConfigurationReader();
}
return instance;
}
}
public class Client {
public boolean doStuff() {
…
ConfigurationReader theOneAndOnlyConfigurationFileReader = Singleton.getInstance();
}
The University of Sydney Page 11
Singleton Example
public class ConfigurationReader2 {
private static ConfigurationReader2 instance = null;
private ConfigurationReader2() { }
public static ConfigurationReader2 getInstance() {
if (instance == null) {
instance = new ConfigurationReader2();
}
return instance;
}
}
public class Client {
public boolean doStuff() {
…
ConfigurationReader theOneAndOnlyConfigurationFileReader = Singleton.getInstance();
theOtherConfigurationFileReader = ConfigurationReader2.getInstance();
}
Do you really always want
one specific instance of one
specific class?
The University of Sydney Page 12
Singleton Alternative Example
public class ConfigurationReader {
public ConfigurationReader() { }
// . . .
}
public class Client {
// Explicit dependency in interface.
// The ‘single’ instance is passed around by reference
public boolean doStuff(ConfigurationReader configurationReader) {
// . . .
}
The University of Sydney Page 13
Decorator Pattern
Object Structural
The University of Sydney Page 14
Structural Patterns (GoF)
Pattern
Name
Description
Adapter Allow classes of incompatible interfaces to work together. Convert the
interface of a class into another interface clients expect.
Decorator Attach additional responsibilities to an object dynamically (flexible
alternative to subclassing for extending functionality)
Façade Provides a unified interface to a set of interfaces in a subsystem. Defines
a higher-level interface that simplifies subsystem use.
The University of Sydney Page 15
Decorator Pattern
– Intent
– Attach additional responsibilities to an object dynamically. Decorators
provide a flexible alternative to sub-classing for extending functionality
– Applicability
– to add responsibilities to individual objects dynamically and
transparently, without affecting other objects
– For responsibilities that can be withdrawn
– When extension by sub-classing is impractical
• Sometimes a large number of independent extensions are possible
and would produce an explosion of subclasses to support every
combination.
The University of Sydney Page 16
Decorator – Structure
The University of Sydney Page 17
Decorator – Structure
The University of Sydney Page 18
Decorator Pattern – Example
– Flying Stickman, flaming mode
– We want to add a button that will set every entity on fire
– Only the visual aspect will change
public class Flamer extends Entity {
Entity entity;
String imagePath = “flame.png”
public Flamer(Entity entity) { this.entity = entity; }
public String getImagePath() { return imagePath; }
public double getXPos() { return entity.getXPos(); }
public double getYPos() { return entity.getYPos(); }
// . . .
}
The University of Sydney Page 19
Decorator Pattern – Example
– Flying Stickman, flaming mode
– Only the decorated methods are overridden
– All other methods are passed through to the decorated object
public class Flamer extends Entity {
Entity entity;
String imagePath = “flame.png”
public Flamer(Entity entity) { this.entity = entity; }
public String getImagePath() { return imagePath; }
public double getXPos() { return entity.getXPos(); }
public double getYPos() { return entity.getYPos(); }
// . . .
}
The University of Sydney Page 20
Decorator Pattern – Example
– Flying Stickman, flaming mode
– Only the decorated methods are overridden
– All other methods are passed through to the decorated object
// …
// Time to burn
List
for (Entity entity: entities) {
Entity decoratedEntity = new Flamer(entity);
newEntityList.add(decoratedEntity);
}
entities = newEntityList;
// …
The University of Sydney Page 21
Decorator Pattern – Why Not Inheritance?
– We want to add responsibilities to individual objects, not an entire
class
– E.g., A GUI toolkit should let you add properties like borders or
behaviours like scrolling to any user interface component
– Is adding responsibilities using inheritance a good design? For
example, inheriting a border class puts a border every subclass
instance
– Why, why not?
The University of Sydney Page 22
Decorator Pattern – Why Not Inheritance?
– Adding responsibilities using inheritance restricts runtime
change, and requires an implementation for every decoration.
– This design is inflexible
• The choice of border is made statically; a client cannot
control how and when to decorate the component with a
border
• More flexible design is to enclose the component in another
object that adds the border
The University of Sydney Page 23
Decorator Pattern – Text Viewer Example
– TextView object has no scroll
bars and border by default
(not always needed)
– ScrollDecorator to add them
– BorderDecorator to add a thick
black border around the
TextView
The University of Sydney Page 24
Decorator Pattern – Text Viewer Example
– Compose the decorators with the TextView to produce both the border and the
scroll behaviours for the TextView
The University of Sydney Page 25
Decorator Pattern – Text Viewer Example
The University of Sydney Page 26
Decorator – Text Viewer Example
– VisualComponent is the abstract class for visual objects
– It defines their drawing and event handling interface
– Decorator is an abstract class for visual components that decorate
the other visual components
– It simply forwards draw requests to its component; Decorator
subclasses can extend this operation
– The ScrollDecorator and BorderDecorator classes are subclasses of
Decorator
– Can add operations for specific functionality (e.g., ScrollTo)
The University of Sydney Page 27
Decorator – Participants
– Component (VisualComponent)
– Defines the interface for objects that can have responsibilities added to
them dynamically
– ConcreteComponent (TextView)
– Defines an object to which additional responsibilities can be attached
– Decorator
– Maintains a reference to a Component object and defines an interface
that conforms to Component’s interface.
– ConcreteDecorator (BorderDecorator, ScrollDecorator)
– Adds responsibilities to the component
The University of Sydney Page 28
Decorator – Collaborations
– Collaborations
– Decorator forwards requests to its Component object. It may
optionally perform additional operations before and after
forwarding the request.
The University of Sydney Page 29
Consequences (1)
– More flexibility and less complexity than static inheritance
– Can add and remove responsibilities to objects at run-time
– Inheritance requires adding new class for each responsibility (increase
complexity)
– Avoids feature-laden (heavily loaded) classes high up in the
hierarchy
– Defines a simple class and add functionality incrementally with
Decorator objects – applications do not need to have un-needed
features
– You can define new kinds of Decorators independently from the
classes of objects they extend, even for unforeseen extensions
The University of Sydney Page 30
Consequences (2)
– Decorator and its component are not identical
– Decorated component is not identical to the component itself – you
shouldn’t rely on object identity when you use decorator
– Many little objects
– Can become hard to learn and debug when lots of little objects that
look alike
– Still not difficult to customise by those who understand them
The University of Sydney Page 31
Façade Pattern
Object Structural
The University of Sydney Page 32
Structural Patterns (GoF)
Pattern
Name
Description
Adapter Allow classes of incompatible interfaces to work together. Convert the
interface of a class into another interface clients expect.
Decorator Attach additional responsibilities to an object dynamically (flexible
alternative to subclassing for extending functionality)
Façade Provides a unified interface to a set of interfaces in a subsystem.
Defines a higher-level interface that simplifies subsystem use.
The University of Sydney Page 33
Façade Pattern
– Intent
– Provide a unified interface to a set of interfaces in a subsystem. It
defines a higher-level interface that makes the subsystem easier to use
– Applicability
– You want to provide a simple interface to a complex subsystem
– There are many dependencies between clients and the implementation
classes of an abstraction
– You want to layer your subsystem. Façade would define an entry point
to each subsystem level
The University of Sydney Page 34
Façade Motivation
A facade object provides a single, simplified interface to the more general
facilities of a subsystem
The University of Sydney Page 35
Façade – Structure
The University of Sydney Page 36
Façade Pattern – Example
class Façade {
subClass1 s1;
subClass2 s2;
public Façade() {
s1 = new subClass1();
s2 = new subClass2();
}
public void methodA() {
s1.method1();
s2.method2();
}
}
class subSystem2 {
public void method2() {
// method body }
}
class subClass1 {
public void method1() {
// method body }
}
How about Client?
Façade façade = new Façade();
façade.methodA();
The University of Sydney Page 37
Façade – Participants
– Facade
– Knows which subsystem classes are responsible for a request.
– Delegates client requests to appropriate subsystem objects.
– Subsystem classes
– Implement subsystem functionality.
– Handle work assigned by the Façade object
– Have no knowledge of the facade; they keep no references to it.
– Collaborations
– Clients communicate with the subsystem by sending requests to Façade, which
forwards them to the appropriate subsystem object(s).
• Although the subsystem objects perform the actual work, the façade may
have to do work of its own to translate its interface to subsystem interfaces
– Clients that use the facade don’t have to access its subsystem objects directly
The University of Sydney Page 38
Consequences
– Simplify the usage of an existing subsystem by defining your own
interface
– Shields clients from subsystem components, reduce the number of
objects that clients deal with and make the subsystem easier to
use.
– Promote weak coupling between the subsystem and the clients
– Vary the components of the subsystem without affecting its clients
– Reduce compilation dependencies (esp. large systems) – when
subsystem classes change
– Does not prevent applications from using subsystem classes if they
need to. Choice between ease of use and flexibility.
The University of Sydney Page 42
Façade Pattern
– Façades can simplify using a series of complicated method calls
and interactions
– Façades can wrap a complex set of packages with a simpler
interface
– Easier to use
– Easier to maintain
– Promote weak coupling with the complex system
– Doesn’t prevent using the complex system directly if needed
The University of Sydney Page 49
References
– Craig Larman. 2004. Applying UML and Patterns: An Introduction to Object-
Oriented Analysis and Design and Iterative Development (3rd Edition).
Prentice Hall PTR, Upper Saddle River, NJ, USA.
– Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
1995. Design Patterns: Elements of Reusable Object-Oriented Software.
Addison-Wesley Longman Publishing Co., Inc., Boston, MA, USA.
The University of Sydney Page 1
Software Design and
Construction 1
(SOFT2201/COMP9201)
Unit/Exam Review
Dr. Martin McGrane
The University of Sydney Page 2
Agenda
– Assessment Review
– Exam Preparation & Info
– Exam Sample Questions
– Advice
The University of Sydney Page 3
Unit of Study Survey – Reminder
– ONLINE survey
– https://student-surveys.sydney.edu.au/students/
https://student-surveys.sydney.edu.au/students/
The University of Sydney Page 4
Assessment Review
The University of Sydney Page 5
SOFT2201/COMP9201 Assessment
What (Assessment)* When (due) How Value
Weekly Exercises Weekly (1-12) Online Exercises (Canvas) 10%
Assignment 1 Week 4 Submission on Canvas 5%
Assignment 2 Week 8 Submission on Canvas 15%
Assignment 3 Week 13 Submission on Canvas 20%
Online Final Exam (See exam timetable) Individual exam 50%
The University of Sydney Page 6
Passing this unit
– To pass this unit you need both two:
– Get at least 50% overall1
– Get at least 40% for your final exam mark2
1 A requirement of all University of Sydney units of study
2 A requirement of all School of CS units of study
The University of Sydney Page 7
Exam Preparation & Info
The University of Sydney Page 8
Exam Preparation
– All materials covered (week 1 to week 12)
– Lecture materials
– Tutorial materials
– Weekly exercises
– Three Individual assignments (i.e., A1, A2 and A3)
– Supporting resources (books, other references)
– Note that libraries, such as JavaFX and SimpleJson, are not
examinable.
The University of Sydney Page 9
Exam Preparation Tools
– Questions can be asked to your tutors during tutorial 12
– Tutorial questions use the exercises as a focus for revision discussion
– Questions can be asked on Ed discussion forum
– Answering and discussing questions about the subject are very helpful to
your own understanding
The University of Sydney Page 10
Exam Information
– Check your personal exam timetable
– The exam is held on an exam-specific Canvas site, to which you
will be added by exam office.
– Structure is ‘short release take-home exam’
– Third party communication or collaboration apps/websites are not
permitted
– 10 minutes reading time + 2 hours writing time + 15 minutes
upload time
– Exam is not supervised but is timed.
The University of Sydney Page 11
Exam Information
– The total marks for this exam are 100
– Two types of questions
– Short answer questions
– Extended response scenario-based questions
– Write your answers clearly and concisely
– Answer all questions
– Read the question and answer what it asks you to answer
The University of Sydney Page 12
Exam Questions
– Duration: 2 hours and 25 minutes (145 minutes). This includes:
– 10 minutes of reading time, but you can start writing whenever you are ready
– you are strongly encouraged to use this time to carefully plan and structure
your response before you start writing.
– 15 minutes of upload time to allow you to upload your files as per your exam
instructions. Do NOT treat this as extra writing time. The upload time must be
used solely to save and upload your files correctly as per the exam
instructions. Manage your time carefully. Check that you have saved and
named your file correctly and uploaded the correct file. If your time runs out
while you are uploading this is not considered a technical issue.
The University of Sydney Page 13
Exam Questions
– Short answer questions
– Answers should be a short paragraph, or code snippets
– Must use the proper or most accurate terminology
– The marker will not ‘interpret’ your answer.
The University of Sydney Page 14
Exam Questions
– Scenario-based questions (Extended response)
– Contain several sub-questions
– May include name, briefly explain, design/model, implement
– Based on contextual information
– Answer as instructed
– Clearly and concisely
– If you make any assumptions about the problem beyond what is
specified, make sure to note these in your answer
The University of Sydney Page 15
Exam Sample Questions
The University of Sydney Page 16
Exam Questions
– E.g., Describe pattern/principle X and compare it to p/p Y
– X is a design pattern that …
– X is generally useful because …, although it has the drawbacks …
– Y is a design pattern that …
– Y is generally useful because …, although it has the drawbacks …
– X differs from Y because …
The University of Sydney Page 17
Exam Questions
– E.g., Apply a design pattern to solve problem Y
– I will use X
– X is a design pattern that …
– X is generally useful because …, although it has the drawbacks …
– X is specifically applicable to Y because …
– … implementation … (if asked for)
The University of Sydney Page 18
Exam Questions
– E.g., Given the following code, state the pattern that has been
used in it. Map the classes in the code to the roles/participants
in the pattern.
– The pattern that has been used in the code is …
– Class X is … (refer to participant name) of pattern …
– Class X is used for/to … (specific roles) in pattern … in the given code
The University of Sydney Page 19
Exam Questions
– E.g., List all classifier names together with attributes and operations
of the UML class diagram of system S. Identify the relationships
among these classifiers.
– Class X
• Attributes: + variableName : String
• Operations: + methodName (par: Z): double
– Interface Y
• Operations: + methodName (par: Z): double
– Relationship:
• Class X implements interface Y
• Y is dependent on Z
The University of Sydney Page 20
Advice
The University of Sydney Page 21
Exam Technique
– Plan how you will allocate time (wisely)
– Use “reading time” to read and understand the question
– Plan time allocation to questions
– Plan the order of answering questions
• E.g. answer easier ones first (quicker ones first?)
– Answer everything (get the “easy marks”)
– Plan your answer, write answers relevant to the questions
– Quality not quantity
– Write clearly and efficiently
– If you are asked to list something, using bullet points is more efficient and easier to read
The University of Sydney Page 22
Exam Technique
– Upload time
– Use “uploading time” to upload your answer
– Check you are uploading the correct file
– Check the file is uploaded
– Check that you submitted the uploaded file
The University of Sydney Page 23
Exam Technique
– If you are uncertain about a question during the exam, answer to the best of your
ability. Do not contact the unit coordinator or other teaching staff during the exam.
– Any assumptions or interpretations must be noted together with your answers
– If you encounter technical difficulties during the exam that you cannot fix, email
canvas. .au with your unit of study code, contact number and SID.
You must contact us before your quiz or assignment has closed for submission. We
cannot provide assistance after submission closes.
– If you encounter technical difficulties during the exam that affect your ability to
complete the exam you will need to describe your problems on a Student
Declaration and apply for special consideration.
– Links to these can be found on the exam page
The University of Sydney Page 24
Good Luck!