Post on 16-Dec-2015
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-1
תוכנה מערכות להנדסהתיכוןאישי פרויקט ופיתוח
Dr. Reuven Gallant
Jerusalem College of
Technology
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-2
The SHADOW
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-3
How did the SHADOW get its name?????
• 2 Theories
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-4
Theory I
•Sikorsky Helicopter Advanced
Demonstrator of Operator Workload
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-5
Theory II
• Jimmy Durante’s radio program and nose!
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-6
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-7
Dessert (if anyone has room)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-8
The SHADOW was top top secret!!!!
• Not members of the U.S. House of Representatives…
• Not even Senators…– Got to see the SHADOW
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-9
The SHADOW was top top secret!!!!
•But the King got to fly in it!
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-10
4 Helicopters were sent to fetch the King from Boston
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-11
It was raining, and the King decided that discretion was the better part of
valour
It was raining, and the King decided that discretion was the better part of
valour
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-12
Our course
Jonah’s course
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-13
Blower
Dual_Speed_Blower
Dual_Speed_Multiheat_Blower
Event Driven Reactive Systems (1): Inherited Behavior
Off
OnSwitchOff
SwitchOn/f()
Off
On
Default
On
Low
High
cool
hot
warm
SwitchOff/k()
SwitchOn
Off
On
High
Low
SwitchOn/f()
SwitchOff/h();k()
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-14
Event Driven Reactive Systems (2)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-15
Event Driven Reactive Systems (3)
IDisplay
ITuner
Radio
theFrequency:Frequency1
theWaveband:Waveband4
Waveband
theFrequency:Frequency5
itsCurrentWaveband
1
itsCurrentFrequency
1
itsDisplay1
itsTuner1
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-16
off>
on
searching
normal
on
autoSearch
manualSearch
tuning
locked
found
tune>
memory>
confirm
selectWhichMemory
C
evFound
evSearch/direction = params->d;
[itsTuner->isStrongSignal()]/GEN(evFound);
tm(20)
[else]/retune();
[IS_IN( autoSearch)]
tm(20)
evTuneDown/theFrequency->down();
evMemory
evTuneUp/theFrequency->up();
evPreset/preset( params->aMemory
evMemory
evPreset/theMemory = params->aMemory;
evOnOff
evOnOff
evWaveband/nextWaveband();
evMemory/itsCurrentWaveband->save( theMemory, theFrequency );
Event Driven Reactive Systems(4)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-17
Event Driven Reactive Systems(5)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-18
What is a (good) Design?
• “Those characteristics of a system …that are selected by a developer in response to the requirements.”
…Some (characteristics) will be implementation-related, … such as software units and logic…to satisfy the requirements.”
MIL-STD-498• TNTWI-WHDI? • We will return to this question throughout the course
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-19
Course Objective (1): to know that good design is
להיות
יותר
חכם
' רדי מפ
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-20
Course Objective (2)To know the state of the art
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-21
Course Objective (3)To take yourselves seriously
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-22
Course Objective (4)To program with models
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-23
What we will learn• to apply ECSAM to Object Oriented Development
– to deepen understanding of Statecharts• solidify knowledge of C++
– and its relation to Software Design
– acquire good coding style conventions (as exemplified in Rhapsody• to learn how to build and understand UML models
– to learn how to work with executable modeling tools• to learn why and how to apply Design Patterns• to learn why and how to design systems with reactive objects• to learn a viable development process for small projects
– Agile Software Development, extreme programming, test first programming, refactoring
• to learn something about personal life management– Stephen Covey’s 7 Habits of Highly Effective People
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-24
What’s confusing about this course?
• Example-based teaching– this is good
• Each example repeats much of what was learned earlier– this is good, provided you keep clear what is old and
what is new.• Examples usually require more than one of the
skills in the previous slide– thus we have to learn (a little bit) of everything at once– this can be confusing!!!!
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-25
Course Syllabus-Software Design• Review of ECSAM (only most relevant parts)• Review and enrichment of statecharts• Introduction to Object Orientation (OOAD)• UML symbology and mapping to Code
– exemplified with Rhapsody• UML real-time approaches
– exercised in Rhapsody• Class Design Principles• Package Design Principles• Non-realtime examples (weather station)• Real-time examples
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-26
Course Syllabus-Personal Software Process
• Personal and Interpersonal Growth and Development (leadership and management)– The 7 Habits of Highly Effective People
• Management and Leadership of Small Projects– eXtreme Programming
• Teamwork– Pair Programming
• Software Requirements Analysis in the Small– Use Cases
• Building in Software Quality– Refactoring
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-27
Course Topics•ECSAM in UML
•Principles of Class Design
•Principles of Package Design
• Case Study with Design Patterns
•Real Time Object Oriented Design
•Model Driven Development
•Executable Models (Rhapsody)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-28
הקורס דרישות
•- חובה בניסוי השתתפותנוכחות•מפלוס • מעבדה !!!)מינוס(עד+ 10תרגלי
20% -!(20%בוחן • אחד ) מועד רק יש מגןסופי • (90%או 70%מבחן בבוחן ) תלוי
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-29
(:1דרישות )- חובה בניסוי השתתפות
הבנת • רמת בין תלות לבודק מיועד statechartהניסוישל מורכבות statechartלבין
• - ב נתמקד והניסוי הקורס statechartsלצורךבהרצאות הקורס בהתחלת
• " נוכחות נרשום ל הנ בהרצאות• . / / לשאלון תשובות תכתוב י ה תלמיד כלשל • ציון על ישפיע לא התשובות של נכונות
. ה/ התלמיד
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-30
נוכחות(: 2דרישות )•--- חובה אינה אבלנוכחות
מאחר וגישת הקורס הוא שונה ומשונה –ומאחר הצלחה בקורס מחייבת הבנה לעומק,
יהיה קשה לרכוש את הידע “יד שניה”. מי שלא משתתף ברציניות בשיעורים ובמעבדות
עלול/ה ליכשל.statechartרישום נוכחות בהרצאות •
רק לצורך המחקר, לא ישפיע על הציון–בכל זאת, כל מי שנוכח בהרצאות הנ"ל תבוא –
עליו ברכה
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-31
( תרגילי מעבדה3דרישות)
ביצוע של התרגילים היא בזוגות )ולא יותר(•כל תלמיד נבדק "בעל פה" בנפרד )לא •
בזוגות( על כל תרגיל תרגילים. )בהמשך ההסבר 10יהיו כ •
(Nנתייחס למספר התרגילים כמשתנה בשם מי שנבחן על כל התרגילים בעוד מועד מקבל עד –
נקודות10תרגיל שמוגש באיחור נחשב תרגיל שלא מוגש– מי שלא נבחן על אף תרגיל בעוד מועד מקבל –
נקודות-20נוסחת נקודות מקסימום לתרגילים היא:–(M*10/N(-)N-M*)20/N
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-32
א(: תרגילי מעבדה3דרישות)
מדיניות התרגילים נראית אכזרית,• אבל זאת אכזריות של רחמנים.•מדיניות התרגילים מיועדת לעודד השקעה •
שוטפת במקום מאמצים יומיים לפני המבחן.בלי מאמצים שוטפים אי אפשר לקבל מה •
שצריך לקבל מהקורס.כל מחזור יש תלמידים שלא שמים לב •
למדיניות התרגילים, ולכן הציון המקסימלי )כמובן רק אם 70שלהם בקורס יהיה
במבחן סופי(100מקבלים במבחן סופי יש הדגש על הבנת התרגילים!!•
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-33
(: בוחן4דרישות)
.20%הבוחן הוא מגן במשקל של •לכן הוא לא חובה.•יהיה רק מועד אחד לבוחן.•לצערי, אין לי זמן לטפל מועדים נוספים על •
אף שזה עלול לפגוע במקרים של העדרות מוצדקת.
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-34
סופי(: 5דרישות) מבחן
מעמיקה • הבנה על הדגש• , בנקודות אבל בסדר שנראה פתרון שכותב מי לכן
, האיכות לפי ציון יקבל הבין לא שהוא מפגין קריטיות. הכמות לפי ולא
•!!!!!!!! פקטור יהיה לא•!!!!!! במבחן זמן הארכת תהיה לאיוביל • הקורס במשך שוטף מאמץ רק לכן
!!!!! גבוה לציון
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-35
סופי מבחן של דוגמא
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-36
הקורס ותוכן במדיניות שינויים
לגבי • להתעדכן תלמיד כל של אחראיות , של בתוכן הקורס של במדיניות שינויים
,' פה בעל נמסר המדע אם בין וכו הקורס ) " אם) בין מעבדה מתרגילי או המרצה י ע
. ברשת או בכתב נמסר המדע
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-37
http://alum.mit.edu/www/rgallant=www-cc.jct.ac.il
=cc/~rgallantrgallant@alum.mit.edu
א208חדר: ויילר 6751016טל:
6432145פקס: :שעות קבלה
1800-1830, 1330-1400יום א', ב', ד'
1330-1400יום ג' במכון טל
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-38
Class symbol in UML(1)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-39
Class symbol in UML(2)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-40
Class symbol in UML(3): Class Name
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-41
Class symbol in UML(4): Attribute
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-42
How do we define attributes?(1):from class features
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-43
How do we define attributes?(2): from attribute features
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-44
Class symbol in UML(5): operation
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-45
How do we define operations?(1):from class features
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-46
How do we define operations?(2): from operation features
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-47
How do we define operations?(3): from operation features
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-48
Generated Code for an Attribute• Save then edit the code for the Display class
Accessor
Mutator
Initial ValueProtected attribute
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-49
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-50
-count : int
+Display)(+isDone():bool
Display+count : int
+Display()+isDone():bool
Display
#count : int
+Display()+isDone():bool
Display
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-51
CG:CGGeneral:GeneratedCodeInBrowser
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-52
// File Display.h#ifndef Display_H #define Display_H class Display { public: Display(); ……..};#endif
Class Source Files
// File Display.cpp
#include "Display.h"
Display::Display() {
//#[ operation Display()
cout << "Hello World" << endl;
//#]
}
……
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-53
What is a component?
Executable
Name
Scope
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-54
What is a Configuration(1)? Name
Current configuration
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-55
What is a Configuration(2)?:Initial Instance
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-56
What is a Configuration(3)?:”Settings”
Instrumentation
Environment
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-57
What is a Package in UML(1)?
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-58
What is a Package in UML(2)?
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-59
What is a reactive object?: Simple Statechart
terminator
actions
timeout
guardsterminator
condition connector
transition
state
default transition
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-60
What comes first?
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-61
Sequence Diagram before execution: What We Expect
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-62
Animated Sequence Diagram: Animated What We Expect
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-63
Useful View Buttons(1)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-64
Useful View Buttons(2)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-65
What is a reactive object?(3)Please enter OMTracer Command>> timestamp
Please enter OMTracer Command>> go idle
OMTracer (0:00:00.000) New instance Display[0]:Display created by main()
OMTracer (0:00:00.000) main() Invoked Display[0]->Start Behavior
OMTracer (0:00:00.000) Display[0] Entered State ROOT
OMTracer (0:00:00.000) Display[0] Invoked print(string = started)
OMTracer (0:00:00.000) Display[0]->print(string = started) Returned
OMTracer (0:00:00.000) Display[0] Entered State ROOT.active
OMTracer (0:00:00.000) Display[0] set tm(200) at ROOT.active
OMTracer (0:00:00.000) Display[0]->Start Behavior Returned
Executable is Idle
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-66
What is a reactive object?(4)Please enter OMTracer Command>> go idle
OMTracer (0:00:00.200) Display[0] Sent to itself Event tm(200) at ROOT.active
OMTracer (0:00:00.200) Display[0] Received from itself Event tm(200) at ROOT.active
OMTracer (0:00:00.200) main() Invoked Display[0]->Take Event Timeout
OMTracer (0:00:00.200) Display[0] Invoked isDone()
OMTracer (0:00:00.200) Display[0]->isDone() Returned
OMTracer (0:00:00.200) Display[0] Exited State ROOT.active
OMTracer (0:00:00.200) Display[0] Invoked print(n = 1)
OMTracer (0:00:00.200) Display[0]->print(n = 1) Returned
OMTracer (0:00:00.200) Display[0] Entered State ROOT.active
OMTracer (0:00:00.200) Display[0] set tm(200) at ROOT.active
OMTracer (0:00:00.200) Display[0]->Take Event Timeout Returned
Executable is Idle
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-67
What is a reactive object?(5)Please enter OMTracer Command>> go idle
OMTracer (0:00:00.400) Display[0] Sent to itself Event tm(200) at ROOT.active
OMTracer (0:00:00.400) Display[0] Received from itself Event tm(200) at ROOT.active
OMTracer (0:00:00.400) main() Invoked Display[0]->Take Event Timeout
OMTracer (0:00:00.400) Display[0] Invoked isDone()
OMTracer (0:00:00.400) Display[0]->isDone() Returned
OMTracer (0:00:00.400) Display[0] Exited State ROOT.active
OMTracer (0:00:00.400) Display[0] Invoked print(n = 0)
OMTracer (0:00:00.400) Display[0]->print(n = 0) Returned
OMTracer (0:00:00.400) Display[0] Invoked print(string = Done)
OMTracer (0:00:00.400) Display[0]->print(string = Done) Returned
OMTracer (0:00:00.400) Display[0] Reached Termination State
OMTracer (0:00:00.400) Display[0]->Take Event Timeout Returned
OMTracer (0:00:00.400) main() Invoked Display[0]->~Display()
OMTracer (0:00:00.400) Display[0]->~Display() Returned
OMTracer (0:00:00.400) Instance Display[0] of class Display deleted by main()
Executable is Idle
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-68
What is a Method? (1)“The design of software is essentially a creative
operation, but the designer of a large system usually requires at least guidelines, and preferably a method...”
(David Budgen, Introduction to Software Design, SEI Curriculum Module, SEI-CM-2-2.1, January 1989, p. 1.)
Method: (Techniques, notation, heuristics, quality factors)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-69
What is a Method? (2)Method: (Techniques, notation, heuristics, quality factors)
EXAMPLE OF METHOD AND ITS COMPONENTS
METHOD: Real-Time Object Oriented Process for Embedded Systems (ROPES)
TECHNIQUE: Dependency Inversion Principle (DIP)
NOTATION: Unified Modeling Language
HEURISTICS:1. Identify Use Cases and Draw Use Case Diagram2. Draw Statechart for each Use Case3. Draw Black Box Scenario Sequence Diagram(s) for each Use Case.4. Propose initial architecture, draw Object Model Diagram5. Map Black Box Scenarios to White box and draw sequence diagrams.6. Perform strategic closure analysis7. Enhance the design to support strategic closure.8. …
QUALITY FACTORS: Open Closed Principle (OCP), …
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-70
Where do quality factors come from?
• Quality is not a matter of aesthetics– quality is axiology
• Quality must be derived from a process goal– axiology is the chambermaid of teleology
• The teleos of object oriented technolgy is effective management of unstable requirements
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-71
Some Basic Questions
• How do we represent requirements?
• How do we represent design?
• How do we move between requirements and design? (process issues)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-72
Answers from the Structured World (1)
Requirements Model (DFD)
CA B
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-73
C
Answers from the Structured World (2)
Alternative Designs (Structure Chart)
A
B
B
A
C
BOSS
B
C
A
C
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-74
C
Answers from the Structured World (2)
A
B
B
A
C
BOSS
B
C
A
C
Alternative Designs (Structure Charts)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-75
ECSAM Review (1)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-76
ECSAM Review (2)
Our course
Jonah’s course
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-77
How do we do it in OO? (1):UML Object Model Diagram if Telephone System
corresponds toECSAM System in its Environment Chart
Phone Company
User
Telephone
*
1
1
1
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-78
How do we do it in OO? (2):UML Use Case Diagram
corresponds to ECSAM S-capabilities Chart
User
Cell Phone Use Cases
Initialize Phone
Edit Phone List Data
Connected Services
Display Text
Receive Text Message
{worst case performance < 2s}
Send Text Message
Receive Call
Make Priority Call
Make Call
Phone Company
Priority User
<<include>>
<<predecessor>>
<<extend>>
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-79
How do we do it in OO? (3):UML/Rhapsody Statechart of “Make Call” Use Case
corresponds to ECSAM S-capability Control Chart
LoggedIn
OffHook
Dialing
TargetBusy
Connected
ConnectingWaitingForPickUp
evPickup/connectLines()
tm(500)/sound(BUSY)
evNextNumber/num=getNextNumberInList()
evPrevNumber/num=getPrevNumberInList()
evBackspace/num=num-digit
evInitiateCall/send(num)
tm(1000)/sound(RINGTONE)
evDigit/num=num+digit
/num="";n=0
evBusy
evRinging
evOnLine/sound(DIALTONE)
evOffLine/sound (NONE)
evOnHook/disconnect()
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-80
How do we do it in OO? (4):UML/Rhapsody Sequence Diagram of ‘sunny day’ Scenario of “Initialize Phone” Use Case
corresponds to ECSAM Operational Scenario
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-81
How do we do it in OO? (5):UML/Rhapsody Sequence Diagram of ‘Failure’ Scenario of “Initialize Phone” Use Case
corresponds to ECSAM Operational Scenario
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-82
How do we do it in OO? (6)Use case: Make Call (from Requirements Document)
Scenario: Successful connection1. User presses the digit buttons to enter the phone number.2. For each digit, the display is updated to add the digit to
the phone number.3. For each digit, the dialer generates the corresponding
tone and emits it from the speaker.4. User presses “Send”5. The “in use” indicator is illuminated on the display6. The cellular radio establishes a connection to the
network.7. The accumulated digits are sent to the network.8. The connection is made to the called party.
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-83
Problem Domain Model: Composite
Telephone
itsSpeaker:Speaker1
itsDisplay:Display1
itsDialer:Dialer1
itsCellularRadio:CellularRadio1
itsMicrophone:Microphone1
itsButton:Button11
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-84
Composition in Browser
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-85
Problem Domain Model:Composite
Telephone
Speaker CellularRadioButtonDialer Microphone Display
itsTelephone1
1
itsTelephone
itsMicrophone
1
1
itsTelephone
itsCellularRadio
1
1
itsTelephone
itsDialer
1
1
itsTelephone
itsSpeaker
1
1itsButton
1
1
itsDisplay
itsTelephone
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-86
Composite in Browser
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-87
Dynamic Requirements Model (Collaboration Diagram)
:Dialer
:Display
:Speaker
Digit:Button
Send:Button
:CellularRadio
2.1. connect()1. digit()
1.1. displayDigit()
1.2. emitTone()
2.1.1. inUse()
2. send()
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-88
Dynamic Requirements Model (Sequence Diagram Version)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-89
Reconcilation of Static and Dynamic Model
:Dialer
:Display
:Speaker
Digit:Button
Send:Button
:CellularRadio
2.1. connect()1. digit()
1.1. displayDigit()
1.2. emitTone()
2.1.1. inUse()
2. send()
+digit(int code):void+send():void
Dialer
+inUse():void+displayDigit():void
Display
+emitTone(int code):void
Speaker
+connect(PNO number):void
CellularRadio
+buttonCode : int+buttonType : tButtonType
+press():void
Button
itsDialer
1
itsCellularRadio
1
itsSpeaker 1
itsDisplay 1
1
itsDisplay
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-90
:Dialer
:Display
:Speaker
Digit:Button
Send:Button
:CellularRadio
2.1. connect()1. digit()
1.1. displayDigit()
1.2. emitTone()
2.1.1. inUse()
2. send()
Reconcilation of Static and Dynamic Model
+digit(int code):void+send():void
Dialer
+inUse():void+displayDigit():void
Display
+emitTone(int code):void
Speaker
+connect(PNO number):void
CellularRadio
+buttonCode : int+buttonType : tButtonType
+press():void
Button
itsDialer
1
itsCellularRadio
1
itsSpeaker 1
itsDisplay 1 1
itsDisplay
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-91
+digit(int code):void+send():void
Dialer
+inUse():void+displayDigit():void
Display
+emitTone(int code):void
Speaker
+connect(PNO number):void
CellularRadio
+buttonCode : int+buttonType : tButtonType
+press():void
Button
itsDialer
1
itsCellularRadio
1
itsSpeaker 1
itsDisplay 1
Initial Object Model (Design?)
+digit(int code):void+send():void
Dialer
+inUse():void+displayDigit():void
Display
+emitTone(int code):void
Speaker
+connect(PNO number):void
CellularRadio
+buttonCode : int+buttonType : tButtonType
+press():void
Button
itsDialer
1
itsCellularRadio
1
itsSpeaker 1
itsDisplay 1
1
itsDisplay
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-92
Designing for Unstable Requirements
Class Design PrinciplesOpen-Closed Principle (OCP)
Liskov Substitution Principle (LSP)
Dependency Inversion Principle (DIP)
Interface Segregation Principle (ISP)
Package Design PrinciplesReuse/Release Equivalence Principle (REP)
Common Reuse Principle (CRP)
Common Closure Principle (CCP)
Acyclic Dependencies Principle (ADP)
Stable Dependencies Principle (SDP)
Stable Abstractions Principle (SAP)
Design Metrics
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-93
Open Closed Principle (OCP)the key to management of unstable requirements
“SOFTWARE ENTITIES )CLASSES, MODULES, FUNCTIONS, ETC.( SHOULD BE OPEN FOR EXTENSION, BUT CLOSED FOR MODIFICATION.”
--Bertrand Meyer, Object Oriented Software Construction, Prentice Hall, 1988, p 23
1. “Open For Extension”.This means that the behavior of the module can be extended. That we can
make the module behave in new and different ways as the requirements of the application change, or to meet the needs of new applications.
2. “Closed for Modification”.The source code of such a module is inviolate. No one is allowed to make
source code changes to it.
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-94
Abstraction is the KeyClosed Client
Open Client
ServerClient 1itsServer
Client
Server
IServer<<Interface>>
1itsIServer
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-95
(Object) ADAPTER SERVER pattern for decoupling Button from Dialer
+buttonPress():void
IButtonServer
<<Interface>>
#code : int
+buttonPress():void
DigitButtonAdapter
+digit(int cod+send():void
Dialer
+buttonPress():void
SendButtonAdapter
+press():void
Button
itsDialer1
itsDialer1
itsIButtonServer
1
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-96
Embedded Avionic Software
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-97
+digit(int code):void
Dialer
+inUse():void+displayDigit():void
Display
+connect(PNO number):void
CellularRadio
+digit():void
IDialerDisplay
<<Interface>>+inUse():void
ICellularRadioDisplay
<<Interface>>
itsIDialerDisplay1 1 itsICellularRadioDisplay
Interface Segregation Principle:Class Adapter Pattern
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-98
Open Closed Principle (OCP)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-99
Open Closed Principle“SOFTWARE ENTITIES )CLASSES, MODULES,
FUNCTIONS, ETC.( SHOULD BE OPEN FOR EXTENSION, BUT CLOSED FOR MODIFICATION.”
Bertrand Meyer, Object Oriented Software Construction, Prentice Hall, 1988, p 23
פתוח להרחבה, אלא סגורה לשינוי
-הערה: רוב החומר ליחידה הזאת נלקח מ
Robert C. Martin, “The Open Closed Principle,” www.objectmentor.com.
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-100
How so?• “Open For Extension”.
– This means that the behavior of the module can be extended. That we can make the module behave in new and different ways as the requirements of the application change, or to meet the needs of new applications.
• “Closed for Modification”.– The source code of such a module is inviolate. No one is allowed to make
source code changes to it.
• איך אפשר לשנות את ההתנהגות של מודול בלי לשנות ???? )source code( את קוד המקור
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-101
Abstraction is the KeyClosed Client
Open Client
ServerClient 1itsServer
Client
Server
IServer<<Interface>>
1itsIServer
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-102
The Shape Abstractionin CListing 1Procedural Solution to the Square/Circle
Problem
enum ShapeType {circle, square};
struct Shape
{
ShapeType itsType;
};
struct Circle
{
ShapeType itsType;
double itsRadius;
Point itsCenter;
};
struct Square
{
ShapeType itsType;
double itsSide;
Point itsTopLeft;
};
// These functions are implemented elsewhere
//
void drawSquare(struct Square*)
void drawCircle(struct Circle*);
typedef struct Shape *ShapePointer;
void drawAllShapes(ShapePointer list[], int n) {
int i;
for (i=0; i<n; i++)
{
struct Shape* s = list[i];
switch (s->itsType)
{
case square:
drawSquare((struct Square*)s);
break;
case circle:
drawCircle((struct Circle*)s);
break;
}}
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-103
The Shape AbstractionOOD solutionListing 2
OOD solution to Square/Circle problem.
class Shape
{
public:
virtual void draw() const = 0;
};
class Square : public Shape
{
public:
virtual void draw() const;
};
class Circle : public Shape
{
public:
virtual void draw() const;
};
void DrawAllShapes(Set<Shape*>& list)
{
for (Iterator<Shape*>i(list); i; i++)
(*i)->draw();
}
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-104
Run Time Type Identification (RTTI)Listing 9RTTI violating the open-closed principle.class Shape {};
class Square : public Shape
{
private:
Point itsTopLeft;
double itsSide;
friend DrawSquare(Square*);
};
class Circle : public Shape
{
private:
Point itsCenter;
double itsRadius;
friend drawCircle(Circle*);
};
void drawAllShapes(Set<Shape*>& ss)
{
for (Iterator<Shape*>i(ss); i; i++)
{
Circle* c = dynamic_cast<Circle*>(*i);
Square* s = dynamic_cast<Square*>(*i);
if (c)
drawCircle(c);
else if (s)
drawSquare(s);
}
Listing 10RTTI that does not violate the open-closed
Principle.class Shape
{
public:
virtual void draw() cont = 0;
};
class Square : public Shape
{
// as expected.
};
void drawSquaresOnly(Set<Shape*>& ss)
{
for (Iterator<Shape*>i(ss); i; i++)
{
Square* s = dynamic_cast<Square*>(*i);
if (s)
s->draw();
}
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-105
Liskov Substitution Principle
(LSP)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-106
LSP-What is it?“FUNCTIONS THAT USE POINTERS OR REFERENCES
TO BASE CLASSES MUST BE ABLE TO USE OBJECTS OF DERIVED CLASSES WITHOUT KNOWING IT.”
The above is a paraphrase of the Liskov Substitution Principle (LSP). Barbara Liskov first wrote it as follows nearly 8 years ago:
“What is wanted here is something like the following substitution property: If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T.” [Barbara Liskov, “Data Abstraction and Hierarchy,” SIGPLAN Notices, 23,5 (May, 1988).]
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-107
A Simple Example of a Violation of LSP
via RTTIvoid drawShape(const Shape& s)
{
if (typeid(s) == typeid(Square))
drawSquare(static_cast<Square&>(s));
else if (typeid(s) == typeid(Circle))
drawCircle(static_cast<Circle&>(s));
}
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-108
Square and Rectangle: a More Subtle Violation.
class Rectangle
{
public:
void setWidth(double w) {itsWidth=w;}
void setHeight(double h) {itsHeight=h;}
double getHeight() const {return itsHeight;}
double getWidth() const {return itsWidth;}
private:
double itsWidth;
double itsHeight;
};
#itsWidth : double#itsHeight : double
+setWidth():void+setHeight():void
Rectangle
+setWidth():void+setHeight():void
Square
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-109
What happens when we call f with an object that is a square?
void Square::setWidth(double w)
{
Rectangle::setWidth(w);
Rectangle::SetHeight(w);
}
void Square::setHeight(double h)
{
Rectangle::setHeight(h);
Rectangle::setWidth(h);
}
Square s;s.setWidth(1); // Fortunately sets the
//height to 1 too.s.setHeight(2); // sets width and
//height to 2, good thing.
But consider the following function:
void f(Rectangle& r){r.setWidth(32); // calls Rectangle::SetWidth}
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-110
Virtual to the rescue!class Rectangle
{
public:
virtual void setWidth(double w) {itsWidth=w;}
virtual void setHeight(double h) {itsHeight=h;}
double getHeight() const {return itsHeight;}
double getWidth() const {return itsWidth;}
private:
double itsHeight;
double itsWidth;
};
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-111
The Real ProblemWhat does the client expect to happen
when g is called with a square?void g(Rectangle& r)
{
r.setWidth(5);
r.setHeight(4);
assert(r.GetWidth() * r.GetHeight() == 20);
}
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-112
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-113
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-114
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-115
Fixed!template <class T>
void PersistentSet::Add(const T& t)
{
itsThirdPartyPersistentSet.Add(t);
// This will generate a compiler error if t is
// not derived from PersistentObject.
}
As the listing above shows, any attempt to add an object that is not derived from PersistentObject to a PersistentSet will result in a compilation error. (The interface of the third party persistent set expects a PersistentObject&).
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-116
Blower
Dual_Speed_Blower
Dual_Speed_Multiheat_Blower
Application of Liskov Substitution Principle to Reactive Objects
Off
OnSwitchOff
SwitchOn/f()
Off
On
Default
On
Low
High
cool
hot
warm
SwitchOff/k()
SwitchOn
Off
On
High
Low
SwitchOn/f()
SwitchOff/h();k()
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-117
To Maximize State Inheritance Compliance with LSP
•New States and transitions may be added freely in the child class
States and transitions defined by the parent cannot be deleted
Actions and activity lists may be changed (added or removed) for each transition and state
Actions and activities may be specialized in the subclass
Substates may not alter their enclosing superstate (including adding a new one)
Transitions may be retargeted to different states Orthogonal components may be added to
inherited states
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-118
Dependency Inversion Principle
(DIP)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-119
The Definition of a “Bad Design”
• The TNTWI-WHDI Criterion– “Why’d you do it that way?”
“That’s not the way I would have done it” • But there is one set of criteria that I think all engineers will agree
with. A piece of software that fulfills its requirements and yet exhibits any or all of the following three traits has a bad design.– It is hard to change because every change affects too many other parts of
the system. (Rigidity)– When you make a change, unexpected parts of the system break.
(Fragility)– It is hard to reuse in another application because it cannot be disentangled
from the current application. (Immobility)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-120
OutputDevice
c
Example: the “Copy” program
Listing 1. The Copy Programvoid copy()
{
int c;
while ((c = ReadKeyboard()) != EOF)
writePrinter(c);
}
Listing 2. The “Enhanced” Copy Program
enum OutputDevice {printer, disk};
void copy(outputDevice dev)
{
int c;
while ((c = readKeyboard()) != EOF)
if (dev == printer)
writePrinter(c);
else
writeDisk(c);
}
copy
readKeyboard
writePrinter
c
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-121
Dependency InversionListing 3: The OO Copy Programclass IReader{public:virtual int read() = 0;};class IWriter{public:virtual void Write(char) = 0;};void Copier::copy(IReader& r, I Writer& w){int c;while((c=r.read()) != EOF)w.write(c);}
Listing 4: Copy using stdio.h#include <stdio.h>#include Copy.hvoid Copier::copy(){int c;while((c = getchar()) != EOF)putchar(c);}
The Copy Program:
+copy():void
Copier
+read():void
IReader
<<Interface>>+write():void
IWriter
<<Interface>>
+write():void
PrinterWriter
+read():void
KeyboardReader
1 1itsIReader itsIWriter
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-122
Case Study in Dependency Management
copy_lowercase
(courtesy of IPL—canata++)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-123
Concrete Classes
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-124
// Hypothetical example of a stub for Keyboard::Keyboard
// Don’t do this in real life!
#define STUB_KEYBOARD_PORTNUM 0x1002
Keyboard::Keyboard() : port(STUB_KEYBOARD_PORTNUM) { }
//
// BAD IDEA! Depends on name and type of private data members
Dependency on Private Variables!!
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-125
Abstract Interface Classes
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-126
Envelope-Letter Pattern
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-127
Conditional Compilation
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-128
The Dependency Inversion Principle:
• What does it say?– HIGH LEVEL MODULES SHOULD NOT
DEPEND UPON LOW LEVEL MODULES. BOTH SHOULD DEPEND UPON ABSTRACTIONS.
– ABSTRACTIONS SHOULD NOT DEPEND UPON DETAILS. DETAILS SHOULD DEPEND UPON ABSTRACTIONS.
• Does layering solve this:– “...all well structured object-oriented architectures
have clearly-defined layers, with each layer providing some coherent set of services through a well-defined and controlled interface.” • [Grady Booch, Object Solutions, Addison Wesley,
1996, p. 54.]
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-129
Not necessarily!!
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-130
:Button :Lamp1. turnOn()
2. turnOff()
+detect():void-getPhysicalState():void
Button
+turnOn():void+turnOff():void
Lamp
1itsLamp
A Simple Example
// file Button.cpp-------------------------#include “button.h”#include “lamp.h”void Button:: detect() { bool isButtonOn = getPhysicalState(); if (isButtonOn) itsLamp->turnOn(); else itsLamp->turnOff();};
//file Button.h---------------------class Lamp;class Button {public : Button (Lamp& l); void detect(); private: bool getPhysicalState(); protected: Lamp * itsLamp;};
// file lamp.hclass Lamp { public: void turnOn(); void turnOff();};
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-131
+turnOn():void+turnOff():void
IButtonServer
<<Interface>>
+turnOn()+turnOff()
Lamp
+detect():void#getState():void
Button
+getState():void
ButtonImplement
itsIButtonServer1
//File Lamp.h---------------------------------------#include “IButtonServer.h”class Lamp : public IButtonServer{ public: virtual void turnOn(); virtual void turnOff();};// File ButtonImplement.h------------------#include “Button.h”class ButtonImplement : public Button{ public: ButtonImplementation (IButtonServer& aButtonServer) virtual bool getState();};// File ButtonImplement.cpp------------------ButtonImplement::ButtonImplement (IButtonServer& aButtonServer) : Button ( aButtonServer) {}
// file: IButtonServer.h----------------------{ public: virtual void turnOn() = 0; virtual void turnOff() = 0;};// file Button.h ---------------------------------class IButtonServer;class Button{ public: Button (IButtonServer& aButtonServer); void detect(); virtual bool getState() = 0; protected: IButtonServer * itsIButtonServer;};// file Button.cpp ---------------------------#include Button.h#include IButtonServer.hButton::Button(IButtonServer& aButtonServer) : itsIButtonServer (& aButtonServer) { }void Button:detect() { bool isButtonOn = getState(); if (isButtonOn) itsIButtonServer->turnOn(); else itsIButtonServer->turnOff();}
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-132
Extending the Abstraction FurtherWhat if Lamp is 3rd Party software that doesn’t have turnOn() and turnOff()
operations?
+turnOn():void+turnOff():void
IButtonServer
<<Interface>>
+turnOn():void+turnOff():void
LampAdapter
+on():void+off():void
Lamp
+detect():void#getState():bool
Button
+getState():bool
ButtonImplement
itsLamp1
itsIButtonServer1
>>Usage<<
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-133
+turnOn():void+turnOff():void
IButtonServer
<<Interface>>
+turnOn():void+turnOff():void
LampAdapter
+on():void+off():void
Lamp
+detect():void#getState():void
Button
+getState():void
ButtonImplement
itsLamp1
itsIButtonServer1
<<Usage>>//File LampAdapter.h--------------------------------#include “IButtonServer”class Lamp;class LampAdapter : public IButtonServer{ public: LampAdapter (Lamp & aLamp); virtual void turnOn(); virtual void turnOff(); Lamp * itsLamp;};//File LampAdapter.cpp-------------------------#include “LampAdapter.h”#include “Lamp.h” LampAdapter::LampAdapter (Lamp & aLamp) : itsLamp( & aLamp) {}LampAdapter::turnOn() {itsLamp->on();}LampAdapter::turnOff() {itsLamp->off();}
//File Lamp.h---------------------------------------#include “LampAdapter.h”class Lamp{ public: Lamp (); virtual void on(); virtual void off(); };//File Lamp.cpp------------------------------------#include “Lamp.h” Lamp::Lamp () { new LampAdapter( *this);}
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-134
Interface Segregation Principle
(ISP)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-135
// file Door.hclass Door {public : virtual void lock()=0; virtual void unlock()=0; virtual bool isOpen()=0;
};
Interface Pollution Consider a security system. Door objects can be locked,
unlocked, and know whether they are open or closed
+lock():void+unlock():void+isOpen():bool
Door
<<Interface>>
+timeOut():void
TimerClient
<<Interface>> +register_(int timeout,TimerClient client):void
Timer*
itsTimerClient
Now consider one such implementation. TimedDoor needs to sound an alarm when the door has been left open for too long. In order to do this, the TimedDoor object communicates with another object called Timer.
// file Timer.hclass TimerClient;class Timer { public: void register_(int timeout, const TimerClient & client)};
// file TimerClient.hclass TimerClient { public: virtual void timeOut ( ) = 0;};
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-136
+timeOut():void
TimerClient
<<Interface>>
+lock():void+unlock():void+isOpen():bool+timeOut():void
Door
<<Interface>>
+lock():void+unlock():void+isOpen():bool+timeOut():void
TimedDoor
+register_(int timeout,TimerClient client):void
Timer
itsTimerClient*
A Common Solution: Timer Client at top of hierarchy
Let’s say we want to provide for cancellation of obsolete timeouts as per the listing below. Do we want to have to modify every derivative of Door?
// file Timer.hclass TimerClient;class Timer {public:void register_ (int timeout, int timeOutId, TimerClient & client) ;};// file TimerClient.h--------------------------------------------------class TimerClient{ public: virtual void timeOut(int timeOutId)=0;};};
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-137
The Interface Segregation Principle
)ISP(
• CLIENTS SHOULD NOT BE FORCED TO DEPEND UPON INTERFACES THAT THEY DO NOT USE.
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-138
+timeOut(int timeOutId):void
TimerClient
<<Interface>>
+lock():void+unlock():void+isOpen():bool
Door
<<Interface>>
+register_(int timeout,int timeOutId,TimerClient client):void
Timer
+isOpen():bool+lock():void+timeOut(int timeOutId):void+unlock():void
TimedDoor
itsTimerClient*
Class Adapter Pattern Solution
// file TimerClient.h class TimerClient {public :virtual void timeOut(int timeout, int timeOutId)=0;};
// file Door.h---------------------------class Door {public : virtual void lock()=0; virtual void unlock()=0; virtual bool isOpen()=0;};
// file Timer.hclass TimerClient;class Timer { public: void register_(int timeout, int timeOutId, const TimerClient & client)};
// file TimedDoor.h---------------------#include “Door.h”;#include “TimerClient.h”;class TimedDoor : public Door, public TimerClient {public : virtual void lock(); virtual void unlock(); virtual bool isOpen(); virtual void timeOut(int timeout, int timeOutId);};
// file Timer.cpp#include “Timer.h”#include “TimerClient.h”…
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-139
Object Adapter Pattern Solution: Delegation
+timeOut(int timeOutId):void
TimedDoorAdapter
+register_(int timeout,int timeOutId,TimerClient client):v
Timer
+lock():void+unlock():void+isOpen():bool+soundAlarm(int timeOutId)
TimedDoor
+timeOut(int timeOutId):void
TimerClient
<<Interface>>
+lock():void+unlock():void+isOpen():bool
Door
<<Interface>>
itsTimedDoor1
<<Usage>>
itsTimerClient*
// file TimedDoor.h--------------#include Door.hclass Door : public Door {public : virtual void lock()=0; virtual void unlock()=0; virtual bool isOpen()=0; virtual void soundAlarm()=0;};
// file TimedDoor.cpp-------------#include TimedDoor.hclass Door : public Door {public : virtual void lock()=0; virtual void unlock()=0; virtual bool isOpen()=0; virtual void soundAlarm()=0;};
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-140
Package Design Principles
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-141
Review: Class Design Principles1. The Open Closed Principle. (OPC) a software module that is designed to be reusable, maintainable and robust must be extensible
without requiring change. Such modules can be created in C++ by using abstract classes. The algorithms embedded in those classes make use of pure virtual functions and can therefore be extended by deriving concrete classes that implement those pure virtual function in different ways. The net result is a set of functions written in abstract classes that can be reused in differ-ent detailed contexts and are not affected by changes to those contexts.
2. The Liskov Substitution Principle. (LSP) Sometimes known as “Design by Contract”. This principle describes a system of constraints for the use of public inheritance in C++. The principle says that any function which uses a base class must not be confused when a derived class is substituted for the base class. This article showed how difficult this principle is to conform to, and described some of the subtle traps that the software designer can get into that affect reusability and maintainability.
3. The Dependency Inversion Principle. (DIP) This principle describes the overall structure of a well designed object-oriented application. The principle states that the modules that implement high level policy should not depend upon the modules that implement low level details. Rather both high level policy and low level details should depend upon abstractions. When this principle is adhered to, both the high level policy modules, and the low level detail modules will be reusable and maintainable.
4. The Interface Segregation Principle. (ISP) This principle deals with the disadvantages of “fat” interfaces. Classes that have “fat” interfaces are classes whose interfaces are not cohesive. In other words, the interfaces of the class can be broken up into groups of member functions. Each group serves a different set of clients. Thus some clients use one group of member functions, and other clients use the other groups. The ISP acknowledges that there are objects that require non-cohesive interfaces; however it suggests that clients should not know about them as a single class. Instead, clients should know about abstract base classes that have cohesive inter-faces; and which are multiply inherited into the concrete class that describes the non-cohesive object.
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-142
What is a Package?
“A general purpose mechanism for organizing elements into groups. Packages may be nested within other packages. A system may be thought of as a single high-level package, with everything else in the system contained in it.”
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-143
Package Dependencies
Dependent Package
Package
In C++ terms, there is at least one class withinthe Dependent Package that has a #includestatement referencing the header file of a classof the Package being depended on.
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-144
Designing with Packages.• Packages allow us to reason about classes at a higher level of abstraction. But
how should we partition classes to allocate them to packages?
• What are the best partitioning criteria?• What are the relationships that exist between packages, and
what design principles govern their use?• Should packages be designed before classes (Top down)?
Or should classes be designed before packages (Bottom up)?• How are packages physically represented? In C++? In the
development environment?• Once created, to what purpose will we put these packages?
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-145
Package Design Principles
The Reuse/Release Equivalence Principle (REP).
THE GRANULE OF REUSE IS THE GRANULE OF RELEASE. ONLY COMPONENTS THAT ARE RELEASED THROUGH A TRACKING SYSTEM CAN BE EFFECTIVELY REUSED. THIS GRANULE IS THE PACKAGE.
The Common Reuse Principle (CRP)
THE CLASSES IN A PACKAGE ARE REUSED TOGETHER. IF YOU REUSE ONE OF THE CLASSES IN A PACKAGE, YOU REUSE THEM ALL.
The Common Closure Principle (CCP)
THE CLASSES IN A PACKAGE SHOULD BE CLOSED TOGETHER AGAINST THE SAME KINDS OF CHANGES. A CHANGE THAT AFFECTS A PACKAGE AFFECTS ALL THE CLASSES IN THAT PACKAGE.
The Acyclic Dependencies Principle (ADP)
THE DEPENDENCY STRUCTURE BETWEEN PACKAGES MUST BE A DIRECTED ACYCLIC GRAPH (DAG). THAT IS, THERE MUST BE NO CYCLES IN THE DEPENDENCY STRUCTURE.
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-146
Methods for Breaking Dependency Cycles
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-147
Package Design with Acyclic Dependencies
MyApplication
MessageWindow
TaskWindow
MyTasks
Task
Database
MyDialogs
Windows
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-148
Package Design with Cyclic Dependencies
MyApplication
MessageWindow
TaskWindow
MyTasks
Task
Database
MyDialogs
Windows
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-149
Weather Monitoring Station: Case Study
This is a preliminary chapter of Object Oriented Analysis and Design with Applications, 2d. ed., Grady Booch, Robert C, Martin, James Newkirk. Copyright © 1998, by Addison Wesley Longman, Inc. No portion of this document may be repro-duced without the written permission of Addison Wesley Longman, Inc.
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-150
Requirements (1)Nimbus-LC Requirements
Usage Requirements
This system shall provide automatic monitoring of various weather conditions. Specifically, it must measure:
• Wind speed and direction
• Temperature
• Barometric pressure
• Relative Humidity
• Wind chill
• Dew point temperature
The system shall also provide an indication of the current trend in the barometric pressure reading. The three possible values include stable, rising, and falling. For example, the current barometric pressure is 29.95 inches of mercury (IOM) and falling.
The system shall have a display which continuously indicates all measurements, as well as the current time and date.
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-151
Requirements (2)24-Hour History
Through the use of a touch screen the user may direct the system to display the 24 hour history of any of the following measurements:• Temperature
• Barometric Pressure
• Relative Humidity
This history shall be presented to the user in the form a line chart (see Figure 3-24)
User Setup
The system shall provide the following facilities to the user to allow the station to be configured during installation.• Setting the current time, date, and time zone.
• Setting the units that will be displayed (english or metric)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-152
Requirements (3)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-153
Initial Sensor Model
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-154
Making Periodic Measurments
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-155
Making Periodic Measurments(2)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-156
Barometric Pressure TrendWhere do we put it?
Algorithm:If the pressure is rising or falling at a rate of at least 0.06 inch
per hour and the pressure change totals 0.02 inch or more at the time of the observation [to be taken once every three hours], a pressure change remark shall be reported.
- Federal Meteorological Handbook No. 1, Chapter 11, Section 11.4.6 (http://www.nws.noaa.gov)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-157
Decoupling the User Interface and the Scheduler: Observer Pattern
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-158
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-159
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-160
Observer also solves our Barometric Pressure Trend Problem!
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-161
Okay, now let’s decouple scheduler from the sensors
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-162
How do we structure the Sensors?use Template Method
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-163
How do we separate hardware API from the system application?
use Bridge pattern
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-164
Creational Issues--hardware dependenciesmain does it
public class WeatherStation
{
public static void main(String[] args)
{
AlarmClock ac = new AlarmClock(new Nimbus1_0AlarmClock);
TemperatureSensor ts =new TemperatureSensor(ac,
new Nimbus1_0TemperatureSensor);
BarometricPressureSensor bps =
new BarometricPressureSensor(ac,
new Nimbus1_0BarometricPressureSensor);
BarometricPressureTrend bpt =
new BarometricPressureTrend(bps)
}
}
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-165
Abstract Factory does it better!
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-166
Only AlarmClock (and the ToolKit) are hardware dependent
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-167
But Sensor construction is only dependent on the Toolkit (no hardware dependence!)
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-168
Getting the ToolKit to create the AlarmClockala Bridge pattern
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-169
Getting the ToolKit to create the AlarmClockala Bridge pattern -the construction process
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-170
Look ma, only one hand!
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-171
Look ma, no hands!
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-172
What’s wrong with this package structure?
04/18/23 All Rights Reserved-Dr. Reuven Gallant Slide I-173
Doctor’s instructions
• Pull main out of the Weather Station Class Package