Upload
alberta-fletcher
View
234
Download
0
Embed Size (px)
Citation preview
1
CSE
2102
CSE
2102
Chapter 4: Software DesignChapter 4: Software Design
Prof. Steven A. DemurjianComputer Science & Engineering Department
The University of Connecticut371 Fairfield Road, Box U-2155
Storrs, CT 06269-2155
[email protected]://www.engr.uconn.edu/
~steve(860) 486 – 4818
(860) 486 – 3719 (office)
2
CSE
2102
CSE
2102
Outline What is Software Design? What is Modularization?
How Can a System Be Decomposed Into Modules? What is a Module’s Interface? What are the Main Relationships Among Modules? What are Software Design Techniques/Information
Hiding? What are Different Types of Modules?
Emerging Software Design Concerns OO and UML Distributed Software Client-Server Architectures Middleware and Service-Oriented Architectures All Will be Covered in Separate Lectures (web)
3
CSE
2102
CSE
2102
What is Software Design? What is Software Design? A design provides structure to any artifact Decomposes a system into parts or components Software design activity decomposes the software into
separately named and addressable software components called modules Modules are integrated to provide a solution to the
problem. Design activity produces a software design document
Describes the system decomposition into modules Software architecture may be produced prior to
design.
4
CSE
2102
CSE
2102
What are Goals of Software Design? Design for change:
Requirements of software product constantly evolve
Anticipate potential changes to during its design Design for likely changes, not every possible
change Look at the future versions/capabilities of software Changes are often after product release, design for
maximum flexibility Maintainability addressed during design:
Ease of modification/adaptation Reduction of perfective maintenance costs
Most challenging responsibility!
5
CSE
2102
CSE
2102
What is Software Design? What is Software Design? Design is the Process of Converting System
Requirements into a Completed Product Software Design is the Output of Process that
Decomposes System into Parts Assigns Responsibilities to Each Part Insure Parts fit Together to Achieve a Global Goal
Design Refers to Both an Activity and the Result of the Activity
Design is an Iterative Activity Start from Initial Point Evolve and Iterate by Adding Features/Capabilities Reach a Steady State Based on …
Design Objectives/Goals Customer’s Input/Feedback
6
CSE
2102
CSE
2102
What is Software Design? Software is Increasingly Refined and Elaborated Until
Detailed Enough to Support Implementation System is Separated into Modules (Components,
Packages, Classes, etc.) Top-Down Decomposition
Large Modules (Components, Packages, Classes) are Decomposed into Smaller Ones
Smaller Ones Implement Larger Ones Larger Ones Composed of Smaller Ones
Bottom-Up Decomposition Lower Level Modules are Defined First These Modules Combined to Form Larger Ones
Either TD or BU – Can Achieve the Same Result
7
CSE
2102
CSE
2102
Examples of TD and BU Design
8
CSE
2102
CSE
2102
What is Software Design? Software Design is
Activity That Bridges Between Requirements and Implementation of Software
Activity That Gives A Structure To The Artifact A Requirements Spec. Document Must Be Designed Given a Structure that Makes It Easy To Understand
and Evolve Software Design Activity
Defined as System Decomposition into Modules Produces a Software Design Document
Describes System Decomposition Into Modules Often a Software Architecture is Produced Prior To
a Software Design
9
CSE
2102
CSE
2102
What is a Software Architecture? Software Architecture
Gross Organization of the System To Be Defined Description Includes Description of
Main Components of A System Relationships Among Those Components Rationale for Decomposition Into its Components Constraints That Must Be Respected By Any Design of
The Components Guides the Development of the Design
What are Some Sample Architectures?
10
CSE
2102
CSE
2102
High-Tech Supermarket System (HTSS)
Automate the Functions and Actions Cashiers and Inventory Updates User Friendly Grocery Item Locator Fast-Track Deli Orderer Inventory Control
User System Interfaces Cash Register/UPC Scanner GUI for Inventory Control Shopper Interfaces Locator and Orderer Deli Interface for Deli Workers
We’ll Introduce and Utilize Throughout Course
11
CSE
2102
CSE
2102
The HTSS Software ArchitectureThe HTSS Software Architecture
ICICICIC
CRCRCRCR
CRCR
CRCR
ILILILIL
ILIL
SDOSDO
SDOSDO EDOEDO
EDOEDO
OrderOrder
PaymentPayment
ItemItemItemDBItemDBLocalLocal
ServerServer
Non-LocalClient Int.
InventoryInventoryControlControl
ItemDBItemDBGlobalGlobalServerServer
OrderDBOrderDB
SupplierDBSupplierDB
CreditCardDBCreditCardDB
ATM-BanKDBATM-BanKDB
IL: Item LocatorIL: Item LocatorCR: Cash RegisterCR: Cash RegisterIC: Invent. ControlIC: Invent. ControlDO: Deli Orderer forDO: Deli Orderer for Shopper/EmployeeShopper/Employee
12
CSE
2102
CSE
2102
Business Process ModelBusiness Process Model
Scanner
Licensing
LicensingDivisionScanningOperator
StoredImages
BasicInformation
Entered
DB
CompletedApplications
HistoricalRecords
Printer
New LicensesNew Appointments
FOI
Letters (RequestInformation, etc.)
Licensing DivisionData Entry Operator
SupervisorReview
DB
DB DB
DB
13
CSE
2102
CSE
2102
Two Important Goals Goal 1: Design for Change (Parnas)
Designers Tend to Concentrate on Current Needs Special Effort to Anticipate Future Changes Design for Likely Changes –Not All Possible Ones Consider Future Versions and Capabilities Remember >60% Cost is Maintenance for Both
Fixing Problems and Adding New Features Think about …
Goal 2: Product Families (Parnas) Think of Current System Under Design as a
Member of Program Family Not Simply Supermarket System, but Inventory
Control for Any Business Plan for Tomorrow’s Products
14
CSE
2102
CSE
2102
Frequent Types of Changes Algorithms (CSE2500)
Replace Inefficient Sorting Algorithm with a More Efficient One
From Bubble Sort to Merge Sort to Quick Sort Choice Made Based on Characteristics of Data
Change of Data Representation From Array to Linked List to Doubly Linked List From Binary Tree to Threaded Tree (See Example) 17% Of Maintenance Costs Attributed To Data
Representation Changes (Lientz And Swanson, 1980)
Change in Data Representation May be a Result of a Change in Algorithm and Vice Versa
15
CSE
2102
CSE
2102
ExamplesExamples
……
16
CSE
2102
CSE
2102
Other Types of Changes Programs written to run on particular abstract machine
Each abstract machine consists of a high-level language, OS calls, and possibly DBMS calls
Portability requires that the abstract machines run on different hardware -- Goal of Java
New releases of OS, compiler, and/or DBMS may require modification to the product.
Hopefully changes in the abstract machine have minimal impact on the product
Technologies that Facilitate Change Open DB Connectivity, JDBC, hibernate Interactions via Client to Web Services
Web Services Description Language (WSDL) Simple Object Access Protocol (SOAP) JavaScript Object Notation (JSON)
17
CSE
2102
CSE
2102
Other Types of Changes Change Of Underlying Abstract Machine
New Release of Operating System New Optimizing Compiler New Version Of DBMS
Change Of Peripheral Devices Embedded, Avionics, Mobile Devices, etc. Changes as a Result of Technology Improvements
Change Of "Social" Environment Change in Insurance Laws New Way to Mobile Devices EURO vs. National Currency in EU
Change Due To Development Process (Transform Prototype into Product)
18
CSE
2102
CSE
2102
Product Families Different Versions Of The Same System
Family of Mobile Phones Members of Family May Differ in Network Standards,
End-user Interaction Languages, … A Facility Reservation System
For Hotels: Reserve Rooms, Restaurant, Conference Space, …, Equipment (Video Beamers, Overhead Projectors, …)
For University: Many Functionalities are Similar, Some are Different (Facilities May Be Free or Not)
Inventory Control Supermarket: UPCs, Track, Stock, Sell, Purchase, … Auto Parts: Same Amazon: Same
19
CSE
2102
CSE
2102
Design Objectives for Program Families Design Entire Family as One System, Not Each
Individual Member of Family Separately Design for Today and Tomorrow
Understand Short Term What is Today’s Product? Features? What are the Deadlines? Deliverables
Factor in Long Term Plan for Tomorrow’s Product What are Future Related Products of Company? Design to Consider these Future Products Ease of Building Future Solutions
What is Available Today for Families? OO: Components and Inheritance Source Code Control/Version Management
20
CSE
2102
CSE
2102
Product Families: A Graphical ViewProduct Families: A Graphical View
RequirementsRequirementsRequirements
1
2
3
Model #1
Model #1
Model #2
5
1
2
3
4 6
7
Model #3
4
1
2
3
Model #2
5
Model #1
4
intermediate design
finalproduct
Sequential Completion: Wrong Way
21
CSE
2102
CSE
2102
Product FamiliesProduct Families
Didn’t identify commonalities of all versionsThe needs of all versions should be
considered in the design stage
1
2
3 5 7
Model #1 Model #2 Model #3
22
CSE
2102
CSE
2102
What is Modularization? Modularization Leverages Off of Software
Architectural Ideas SW Architectures Decompose System into
Interacting Components (Previous Examples) Typically, These Components Exist as Independent
Interacting Programs on Hardware Platforms Modularization Explores the Decomposition of
These Components into Interacting Modules Module:
Well-defined Component of Software System Part of System that Provides Set of Services To
Other Modules Services are Computational Elements Available for Use
by Other Modules Modules Publish Services and Import Services
23
CSE
2102
CSE
2102
Example of Modularization Recall the Cash Register
Component of HTSS CR Contains Modules
UPC Scanner Record Item Sold
Reduce Inventory Add to Receipt Add to Profile on
Customer Payment
Coupons Cash/Debit/Credit
Receipt These Modules Interact
with One Another and HTSS Components
24
CSE
2102
CSE
2102
What are Key Modularization Concepts? What is Tracked for Various Modules?
UPC Scanner, Record Item Sold, Payment, Receipt Interface:
Exported for Use by Other Modules UPC Scanner Exports
Scan Function Returns UPC Code, Item Name, Price ItemDB Exports
ItemQuery Function Returns Name, Price given UPCImported for Use by Specific Module UPC Scanner Imports
ItemQuery Function of ItemDB Payment Imports
Functions of CreditCard and ATMBankDB Exports
25
CSE
2102
CSE
2102
What Does this Represent?
The Client/Server Paradigm!
UPC Scanner – Client that Requests Services ItemDB – Server that Provides Services Establishes Contract Between Modules!
UPC ScannerUPC Scanner ItemDBItemDB
ClientClient ServerServer
Imports from ItemDBImports from ItemDBAnd Other ModulesAnd Other Modules
Exports for use byExports for use byUPC Scanner and UPC Scanner and
Other ModulesOther Modules
USESUSES
26
CSE
2102
CSE
2102
Another Example of Modules Consider an OS with:
File System, Disk I/O Subsystem, DBMS Network Server, GUI, Compilers, Desktop Tools
From Everyday User Perspective:
From Software Engineer Perspective:
File SystemFile System DBMSDBMS
Desktop ToolsDesktop ToolsGUIGUI
File SystemFile System DBMSDBMS
Desktop ToolsDesktop ToolsGUIGUI
CompilersCompilers Network ServerNetwork Server
Disk I/O SubsystemDisk I/O Subsystem
27
CSE
2102
CSE
2102
Impact of Modularization Pervasive Throughout Software and Computing Client/Server/Import/Export/USES have Contexts
OO/Java – Client/Server Classes, Public Interfaces (Export), Import XX.XX.* (Import), …
Web-Based Setting – Client/Server Applications, Clients Use (Import) Services, Servers Provide Services (Export)
Middleware – JINI, CORBA, .NET At Design/Conceptual Level, We Must Understand:
What Does Each Module Provide (Export)? What Does Each Module Need (Import)? What Does Each Module Hide (Implementation)? How to Modules Depend on One Another (Uses,
Is_Component_Of, and Comprises Relations)
28
CSE
2102
CSE
2102
Modules and Relations Let S be a Set of Modules
S = {M1, M2, . . ., Mn} A Binary Relation r on S is a subset of
S x Sfor Defining Relations Among Modules
If Mi and Mj are in S, <Mi, Mj> r can be written as Mi r Mj
Transitive Closure r+ of r Mi r+ Mj iff
Mi r Mj or Mk in S s.t. Mi r Mk and Mk r+ Mj The Relation r Forms a hierarchy iff there are no Two
Elements Mi, Mj s.t. Mi r+ Mj Mj r+ Mi
29
CSE
2102
CSE
2102
Relations Relations can be Represented as Graphs A Hierarchy (Lattice) is a DAG (directed acyclic
graph)M1
M2M3
M4
M1,1 M1,2 M1,3
M1,2,1 M1,2,2
M1,2,1,1
M
M M
M M
M
1
2 3
4 5
6
a) b)
a graph
a DAG
30
CSE
2102
CSE
2102
The USES relation Defined by Parnas Module Mi USES Module Mj:
Mi requires the correct operation of Mj. Mi can access the services exported by Mj through its
interface. Mi depends on Mj to provide its services
For example, Mi calls a routine exported by Mj. Mi is a client of Mj Mj is a server of Mi
USES relationship is statically defined. Determined at design time rather than
execution/runtime
31
CSE
2102
CSE
2102
Hierarchy and the USES relation USES relation should be a hierarchy A hierarchical USES relations defines a system
through levels of abstraction The level of a module is
0 if that module is used by no other module i, where i is the length of the longest DAG path from a
level 0 to current module Mi is at a higher level than Mj, iff i > j
Hierarchal uses relation makes the software easier to: Understand, Apply separation of concerns, and
Test If USES relation is not a hierarchy, then cycles exist in
the graph, and individual modules cannot be tested unless all the modules in the cycle are working
32
CSE
2102
CSE
2102
The USES Relation Desirable Property - USES should be a Hierarchy
Makes Software Easier to Understand We Can Proceed From Leaf Nodes (Who Do Not Use
Others) Upwards Build and Test
With Cycles, Build and Test Must Occur After all Modules in the Cycle are Coded
With Hierarchy – Separation of Concerns
33
CSE
2102
CSE
2102
Hierarchy Organizes the Modular Structure through Levels of
Abstraction Each Level defines an Abstract (Virtual) Machine for
the Next Level, and can be Defined Precisely Mi has level 0 if no Mj exists s.t. Mi r Mj Let k be the maximum level of all nodes Mj s.t. Mi
r Mj. Then Mi has level k+1 In Hierarchy:
Fan-Out is Outgoing Edges of a Module Fan-In is the Incoming Edges from Other Modules Low Fan-In, High-Fan Out Preferable – Why?
Coupling and Cohesion!
34
CSE
2102
CSE
2102
Relations Between Modules
Relations Can Describe the Dependencies that Exist Among Modules w.r.t. Composition
X IS_COMPONENT_OF Y Bottom-Up Composition Y consists of Several Modules, of which one is X
B COMPRISES A Top-Down Composition Inverse of IS_COMPONENT_OF
MS,i={Mk|MkSMk IS_COMPONENT_OF Mi}we say that MS,i IMPLEMENTS Mi
35
CSE
2102
CSE
2102
Graphically:Graphically:
M1
M M
M MM M M
2 4
5 67 8 9
M3
M MM M M5 67 8 9
M2 M3 M4
M1
(IS_COMPONENT_OF) (COMPRISES)
Each Forms a Hierarchy (DAG)
36
CSE
2102
CSE
2102
Modules: Interface vs. Implementation Interface:
Public portion, or the portion accessible outside the module Provides information about what services the module offers Hides how those services are implemented Clients only need to see the interface to use the module Module is said to “export” the services Client, or the user of the module “imports” the services Acts as a contract between the module and its clients
Implementation: Private portion, or the portion accessible inside the module “How” the exported service is implemented Implementation is hidden from the clients, may be
composed of other modules of actual code Separation of concerns is supported by division between a
module’s interface and implementation
37
CSE
2102
CSE
2102
Interface vs. Implementation To Understand Nature of USES, we Need to Know
What a Used Module Exports Through Its Interface Client Imports Resources Exported by Its Servers Modules Implement Exported Resources Implementation Hidden From Clients
interface is like the tip of the iceberg
38
CSE
2102
CSE
2102
Interface, Implementation, and Hiding In Support of Relations (Uses, Is_Component_Of, and
Comprises), Modules Share Vehicle of Sharing: Interface
Set of Services (Operations) Module Can Perform Subset is Exported for Use by Other Modules Module Imports Services from Other Modules
Internally, Module Implements Its Services Separation of Concerns:
Differentiates Between the Exported Services Operations and Their Signatures Signature: Name, Parameters and Types, Return
Hidden Implementation that Realizes Services
39
CSE
2102
CSE
2102
Interface, Implementation, and Hiding When a Module X Uses a Particular Module Y, X
Only Needs Y’s Interface, Not its Implementation Interface is a Contract Between X and Y Client Modules Rely on this Unchanging Interface Akin to:
Class Depending on Public Interface of another Class Web App (Browser) Depending on the Interface of a
Web Server Changes Strongly Discouraged (Deprecated APIs)
Module Y’s Implementation May be Composition of Other Modules or Actual Code Code Changes to Implementation Allowed as Long
as Exported Interface Remains Unchanged Additions to Interface Allowed
40
CSE
2102
CSE
2102
Modules: Interface vs. Implementation What goes in the public interface? What goes in the hidden implementation? Interface design considerations:
Interface must convey to the client the services that it provides
Too much information in the interface increases overall system complexity
Internal knowledge in the interface may cause change in the implementation to affect interface
Not enough information in the interface, module may not provide required services
Interface design depends on the needed services provided and the information the clients will not use
Identification of likely changes is necessary, since that goes in the implementation
41
CSE
2102
CSE
2102
Module: Interface vs. ImplementationModule: Interface vs. Implementation
Symbol table
GET(Varname) returns hex
PUT(Varname,value) returns hex
NOTIFY(Varname,size)
Retrieve value
Store new value
New entry creationsize = #of entries
it represents
Unnecessary information occurs when the location of the variable isreturned in GET(Varname).
42
CSE
2102
CSE
2102
Modules: Interface vs. Implementation Clear distinction of interface and implementation
supports rapid prototyping Initial version may be a “quick and dirty”
implementation of the service Allowed scope of future changes:
Interface must remain unchanged Initial “quick and dirty” version replaced by a
more efficient one No impact on clients of the modules
Easy to evolve initial prototype into a final product
43
CSE
2102
CSE
2102
Modules: Interface vs. Implementation Module supports information hiding by making a clear
distinction between the interface and the implementation.
Information hiding is a global design principle. It states that:
Encapsulate changeable design decisions as implementation secrets within module implementations.
Clients or users of modules are not exposed to the implementation secrets Secrets can be changed freely without affecting the
clients and the system structure. Basis for decomposing a system into modules.
44
CSE
2102
CSE
2102
Modules: Interface vs. Implementation Policies are used to implement high-level design
decisions They should be hidden in the implementation.
Separation of policy vs. mechanism Policies may be separated from mechanism: Mechanism:
Ability to suspend and resume tasks in a concurrent system
Policy How do we select the next task to resume?
Different scheduling policies are available They may be hidden to the clients They may be encapsulated as module secrets
45
CSE
2102
CSE
2102 Reduces complexity, by providing a systematic means of breaking problems into sub-problems
Facilitates change – critical aspect of software maintainability
Results is faster implementation by encouraging parallel developments of different parts of a system
Supports reuse of existing modules in new systems
Advantages of Modular Designs
46
CSE
2102
CSE
2102
Properties of Modular Designs Each module should be functionally independent:
Addresses a specific sub-function of requirements and has a simple interface when viewed from the other parts of the system structure
Independence is measured using two criteria: Cohesion - Indication of the degree to which a
module focuses on just one thing Coupling - Indication of the degree to which a
module is connected to other modules and to the outside world
Good design has high cohesion and low coupling
47
CSE
2102
CSE
2102
Top-down Design StrategyTop-down Design Strategy
Large modules are decomposed into smaller modules which are
said to implement the large modules
General Specific
48
CSE
2102
CSE
2102
Bottom-up Design StrategyBottom-up Design Strategy
Pieces Compose
49
CSE
2102
CSE
2102
Top-down vs. Bottom-up Design Strategy Information hiding proceeds “bottom-up” Iterated application of IS_COMPOSED_OF relation
to modules proceeds “top-down” Bottom-up strategy:
Lowest level modules are combined to form larger modules
Top-down vs. bottom-up: In practice, a combo of both approaches is used Known as the “yo-yo” design
No matter what the design process followed is, the documentation should always be organized in a top-down manner
50
CSE
2102
CSE
2102
Procedure Enter;Procedure Leave;
const nul;
Const maxbuf;Var size, front, …;Procedure succ;
…Procedure bodies;
…initialization
Examples of ModulesExamples of Modules
Procedure Insert;Procedure Find;
Const Limit;Var tab, avail;
…Procedure bodies
…initialization
MODULE Table MODULE Buffer
51
CSE
2102
CSE
2102
Implementation of ModulesImplementation of Modules
definition MODULE Table; export qualified insert, find;
procedure insert (x: integer): boolean; procedure find (x: integrer): boolean;end table.
implementation MODULE Table; // Data structures (e.g., list, array) to // hold elements of table procedure insert (x: integer): boolean; //implementation of insert end insert;
procedure find (x: integrer): boolean; //implementation of find end find;
begin //initialization of data structure for table end;end table.
52
CSE
2102
CSE
2102
Designing Module Interfaces What Goes in the Public Interface of Module X?
Convey to Client Services Provided by X Too Much Information in Interface Increases
Overall System Complexity Including Internal Implementation Detail May
Cause Implementation change to Affect Interface Not Enough Information
Module X Not Used Correctly or at All Prototyping Process - Once an interface is defined
Implementation can be Done First Quickly and Potentially Inefficiently to Allow
Interface Users to Try and See if All Services Available Progressively turned into the Final Version
Initial Prototype that Evolves into Final Product
53
CSE
2102
CSE
2102
Designing Module Interfaces How is Evolution Supported? Similar to OO!
Module’s Abstract Interface hides Implementation Implementation can Change (Array to List)
without Impacting Interfaces Interface can be Extended as Long as Prior
Services still Work Module’s Final Implementation can be Delayed
Key Issue: Identify Module Features Most Likely to Change Isolate those Features in Implementation
54
CSE
2102
CSE
2102
Designing Module Interfaces Interface Must Insulate Users for All Possible Changes Policy Changes Must Also be Encapsulated
Suppose List of Mailing Labels Printing List in Alphabetical Order – Interface Whether the List is Kept Sorted, Sorted then
Printed, etc. – Hidden Implementation Policies May be Separated From Mechanisms
Mechanism - Ability to Suspend and Resume Tasks in Concurrent System
Policy - How Do We Select Next Task To Resume? Different Scheduling Policies are Available They May Be Hidden to Clients They Can Be Encapsulated as Module Secrets
55
CSE
2102
CSE
2102
Design Notations for Modules Notations allow Designs to be Described Precisely
At Design Level, English is too Ambiguous to Fully Describe Software Design
Like a Notation that can Facilitate Transition to Implementation (Writing Code)
Still no Acceptable Standard Notations can be Textual or Graphic We Illustrate two Sample Notations
TDN (Textual Design Notation) GDN (Graphical Design Notation)
We Briefly Discuss the Notations Provided by UML
56
CSE
2102
CSE
2102
TDN TDN is Loosely Based on Ada – Similarities to Other
Languages as Well Three Parts
Interface Description What is Exported (Variables, Operations, Types, etc.) Comments to Describe Protocols, Exported Resource,
Other Restrictions (e.g., Time Availability of Service) Uses
Names of Other Modules that are Used Implementation
Description List of Internal Components via Is_Composed_Of
57
CSE
2102
CSE
2102
An Example in TDN Client Views Export Portions Only TDN Must Support Consistency and Completeness
R and T must be Defined to Implement X Y and Z must be Available (Import)
58
CSE
2102
CSE
2102
An Example in TDN - Continued Notes:
Exporting of Structure (K) and Type (B) in Module R Uses Indicates all Dependencies Among Modules
59
CSE
2102
CSE
2102
Another Example: CompilerAnother Example: Compiler
module COMPILERexports procedure MINI (PROG: in file of char;
CODE: out file of char);MINI is called to compile the program stored in PROG and produce the object code in file CODE
implementationA conventional compiler implementation. ANALYZER performs both lexical and syntactic analysis and produces an abstract tree, as well as entries in the symbol table; CODE_GENERATOR generates code starting from the abstract tree and information stored in the symbol table. MAIN acts as a job coordinator.
and is composed of ANALYZER, SYMBOL_TABLE,ABSTRACT_TREE_HANDLER, CODE_GENERATOR, MAIN
end COMPILER
60
CSE
2102
CSE
2102
Other Compiler ModulesOther Compiler Modules
module MAINuses ANALYZER, CODE_GENERATORexports procedure MINI (PROG: in file of char;
CODE: out file of char);…end MAIN
module ANALYZERuses SYMBOL_TABLE, ABSTRACT_TREE_HANDLERexports procedure ANALYZE (SOURCE: in file of char);
SOURCE is analyzed; an abstract tree is produced by using the services provided by the tree handler, and recognized entities, with their attributes, are stored in the symbol table....
end ANALYZER
61
CSE
2102
CSE
2102
Other Compiler ModulesOther Compiler Modules
module CODE_GENERATORuses SYMBOL_TABLE, ABSTRACT_TREE_HANDLERexports procedure CODE (OBJECT: out file of char);
The abstract tree is traversed by using the operations exported by the ABSTRACT_TREE_HANDLER and accessing the information stored in the symbol table in order to generate code in the output file.…
end CODE_GENERATOR
62
CSE
2102
CSE
2102
GDN Graphical Notations are Easier to Read & Understand CSE is Dominated by Graphical Notations:
ER, DFDs, Petri Nets, FSM, etc… UML and its 13 Diagrams (UML 2.0).
X
Y
Z A B
R T Module Module
Module
Module
Module
C
63
CSE
2102
CSE
2102
X's DecompositionX's Decomposition
X
Y
Z B C
R T Module Module
Module
Module
Module
A
K
64
CSE
2102
CSE
2102
Standard Categories of Modules Functional Modules
Traditional Form Of Modularization Provide A Procedural Abstraction Encapsulate An Algorithm
Sorting Module, Fast Fourier Transform Module, … Libraries
A Group Of Related Procedural Abstractions Mathematical Libraries Implemented By Routines Of Programming Languages
Common Pools Of Data Data Shared By Different Modules
Configuration Constants The COMMON FORTRAN Construct
65
CSE
2102
CSE
2102
Abstract Objects Abstract Objects
Objects Manipulated via Interface Functions Data Structure Hidden From Clients Maintains a State
Two Identical Calls May Produce Different Results Library: Two Identical Calls Produce Same Results
Example Stack of Integers Interface: Push, Pop operations Implementation: Array or Linked List Two Successive Pops on Full Stack May Return
Two Different Values
66
CSE
2102
CSE
2102
Abstract Data Types (ADT) ADT is Module Describes a Set of Behavior From
Which Specific Instances can be Generated Set of Operations to Manipulate Instances Encapsulate the Implementation
indicates that details of thedata structure are hidden
to clients
67
CSE
2102
CSE
2102
ADTs ADTs at Implementation Level:
Correspond to Java and C++ Classes May also be Implemented by Ada Private Types
and Modula-2 Opaque Types May Add Notational Details to Specify if Certain
built-in operations are Available by Default on Instance Objects of the ADT := to Assign an ADT Instance to Variable = to Compare Two ADT Instances
68
CSE
2102
CSE
2102
Another ADT Example Model Cars Waiting for Gas (in our Future?) How is FIFO_CARS Used?
Assumes Existence of CARS Modulemodule FIFO_CARSuses CARSexports
type QUEUE : ?; procedure ENQUEUE (Q: in out QUEUE ; C: in CARS);procedure DEQUEUE (Q: in out QUEUE ; C: out CARS);function IS_EMPTY (Q: in QUEUE) : BOOLEAN;function LENGTH (Q: in QUEUE) : NATURAL;procedure MERGE (Q1, Q2 : in QUEUE ; Q : out QUEUE);This is an abstract data-type module representing queues of cars, handled in a strict FIFO way; queues are not assignable or checkable for equality, since “:=” and “=” are not exported.…
end FIFO_CARS
69
CSE
2102
CSE
2102
Generic Modules Many Applications Employ the Same Abstraction
(Module) in Different Contexts Stack of Integers, Strings, Employees, etc.
Generic Module Single Abstract Description that is Paramterizable
by Type (Integer, String, CAR, etc.) Shared Interface and Single Implementation Once Tested, Provides Stability and Consistency
for Usage by Entire Software Team Reduces the Impact of Changes (From Array to
Linked List – all Benefit) Highly Reusable
70
CSE
2102
CSE
2102
Generic Modules Note the Parameterization by T
Instantiation as:
module INTEGER_STACK_2 is GENERIC_STACK_2 (INTEGER)
Support for Generic Modules: Templates in C++ Interface Inheritance in Java
generic module GENERIC_STACK_2. . .
exportsprocedure PUSH (VAL : in T);procedure POP_2 (VAL1, VAL2 :
out T);…
end GENERIC_STACK_2
71
CSE
2102
CSE
2102
Design for Change In Practice, there Must be Programming Techniques
that Allow for Changes without Need to Recompile Configuration Constants
Factoring Constant Values into Symbolic Constants is a Common Implementation Practice #define in C #define MaxSpeed 5600
Java/C++, Define System_Constant Class: DB Port, Name, Internet Location, etc. System Constants and Identifiers All are Stored in ASCII File on Local Machine Start Up Create Instance of System_Constant Load Instance from File Change File – No Need to Recompile
72
CSE
2102
CSE
2102
Design for Change Conditional Compilation in C, C++ (C#?)
..source fragment common to all versions...
# ifdef hardware-1...source fragment for hardware 1 ...# endif#ifdef hardware-2...source fragment for hardware 2 ...# endif
Software Generation Compiler Compilers (Lex, Yacc) Automatically
Regenerate Code when Change in Specification GUI Construction Tools Allow Drag and Drop for
GUI Components and Generate Code
73
CSE
2102
CSE
2102
Stepwise Refinement A Systematic, Iterative Program Design Technique
that May Lead to Software that is Hard to Evolve At Each Step, Problem P Decomposed Into
Sequence of Sub-problems: P1; P2; …Pn A Selection: If (Cond) Then P1 Else P2 An Iteration: While (Cond) Do_something
Utilizes a Natural langauge Like Description Overall Problem is represented by Rewriting Each
Subproblem into the Overall Structure Intended for Programming-in-the-Small (or for
Programming Individual Methods)
74
CSE
2102
CSE
2102
Selection SortSelection Sort
Step 1let n be the length of the array a to be sorted;i := 1 ;while i < n loop
find the smallest of ai .. .an, and exchange it with the element at position i;i := i + 1;
end loop;
75
CSE
2102
CSE
2102
Step 2let n be the length of the array a to be
sorted;i := 1 ;while i < n loop
j := n;while j > i loop
if a(i) > a(j) theninterchange the
elements at positions j and i ;
end if;j := j - 1;
end loop;i := i + 1;
end loop;
Selection SortSelection Sort
76
CSE
2102
CSE
2102
Step 3let n be the length of the array a to be
sorted;i := 1 ;while i < n loop
j := n;while j > i loop
if a(i) > a(j) thenx := a(i); a(i) := a(j); a(j) := x;
end if;j := j - 1;
end loop;i := i + 1;
end loop;
Selection SortSelection Sort
77
CSE
2102
CSE
2102
Decomposition Tree Stepwise Refinement Process May be Depicted by a
Decomposition Tree (DT) Root Labeled By Name of Top Problem Subproblem Nodes Labeled as Children of Parent
Node Corresponding To Problem Children From Left To Right Represent Sequential
Order Of Execution If and While Nodes Denoted By Suitable
Decoration
78
CSE
2102
CSE
2102
ExampleExampleStep 1
P; P problem to solveStep 2
P1; P2; P3; P decomposed into sequence Step 3
P1; while C loop
P2,1; P2 decomposed into a loop end loop;P3;
Step 4P1; while C loop
if C1 then P2,1 decomposed into selectionP2,1,1;
else P2,1,2;
end if;end loop;P3;
79
CSE
2102
CSE
2102
Corresponding DTCorresponding DT
P
P 1 P
2 P 3
P 2,1
P 2,1, 1 P
2,1, 2
C
C 1 not C
1
80
CSE
2102
CSE
2102
Stepwise Refinement Stepwise Refinement a Programming Technique, Not
a Modularization Technique When Used to Decompose System Into Modules
Tends to Analyze Problems In Isolation, Not Recognizing Commonalities
Does Not Stress Information Hiding Does Not Consider Generalization Across
Subproblems Top Level Function Not Clearly Identifiable
No Attention Paid to Data (Decomposes Functions) Enforces Premature Commitment To Control Flow
Structures Among Modules However, Code Written with Stepwise Refinement is
Clear and Easily Understood
81
CSE
2102
CSE
2102
Another Example with Various Techniques Consider a Program Analyzer First – Stepwise Refinement
Step 1Recognize a program stored in a given file f;
Step 2
correct := true;analyze f according to the language
definition;if correct then
print message "program correct";else
print message "program incorrect";end if;
82
CSE
2102
CSE
2102
Step 3 correct := true;perform lexical analysis:
store program as token sequence in file ft and symbol table in file fs, and set error_in_lexical_phase accordingly;
if error_in_lexical_phase then correct := false;
elseperform syntactic analysis and set Boolean variable error_in_syntactic_phase accordingly:if error_in_syntactic_phase then
correct := false;end if;
end if;if correct then
print message "program correct";else
print message "program incorrect";end if;
Stepwise Refinement (Continued)
83
CSE
2102
CSE
2102
What is the Problem with This Solution? Step 3 Differentiates Between Lexical and Syntax
Analysis Lexical Analysis First on the Entire Program If Successful, then Syntax Analysis
Thus – it is a Two Pass Solution If First Pass Fails, Second Pass Not Checked Lexical Failure Means no Syntax Check
Suppose we Want to Switch to a Process Driven by Syntax Analysis Syntax Analyzer Requests a Token from Lexical
Analyzer Parsing and Lexical Analysis in Single Pass Everything Changes!!!
84
CSE
2102
CSE
2102
An Alternative Design via Modules Module CHAR_HOLDER
Hides Physical Representation of Input File Exports Operation to Access Source File on A
Character-by-Character Basis Module SCANNER
Hides Details of Lexical Structure of the Language Exports Operation to Provide Next Token
Module PARSER Hides Data Structure Used To Perform Syntactic
Analysis (Abstract Object PARSER)
85
CSE
2102
CSE
2102
Top-Down vs. Bottom-up Information Hiding Proceeds Bottom-up Iterated Application of IS_COMPOSED_OF Proceeds
Top-Down Stepwise Refinement is Intrinsically Top-down
Which One Is Best? In Practice, People Proceed in Both Directions
Yo-yo Design Goes Back and Forth Between Both Organizing Documentation as a Top-down Flow
May Be Useful For Reading Purposes, Even If The Process Followed Was Not Top-down
86
CSE
2102
CSE
2102
Handling Anomalies Defensive Design – Plan For Failure as Part of Design A Module is Anomalous if it Fails to Provide the
Service As Expected and as Specified in is Interface An Exception MUST Be Raised When Anomalous
State is Recognized If Anomaly is Detected …
Module M Should Fail and Raise an Exception if One Of Its Clients Does Not Satisfy the Required
Protocol For Invoking One Of M’s Services M Does Not Satisfy the Required Protocol When Using
One Of Its Servers, and the Server Fails Hardware Generated Exception (Division By Zero)
87
CSE
2102
CSE
2102
What A Module Can Do Before Failing Before Failing, Modules May try to Recover From
Anomaly by Executing Some Exception Handler (EH) Local Piece of Code that tries to Recover From
Anomaly (If Successful, Module Doesn’t Fail) Or May Simply Do Cleanup of State and Let the
Module Fail, Signaling an Exception to Its Client
88
CSE
2102
CSE
2102
Case Study – MIDI Compiler Block Structured Prog. Language that Needs a Symbol
Table Module for Block Static Nesting Version 1 of the Symbol Table
89
CSE
2102
CSE
2102
Problem with Version 1 Version 1 is Not Robust Defensive Design should be Applied Exceptions Must be Raised in Numerous Cases:
INSERT: Insertion Cannot Be Done Because Identifier with Same Name Already Exists in Current Scope
RETRIEVE And LEVEL: Identifier with Specified Name Not Visible
ENTER_SCOPE: Maximum Nesting Depth Exceeded
EXIT_SCOPE: No Matching Block Entry Exists
90
CSE
2102
CSE
2102
Generic List Management ModuleGeneric List Management Module
91
CSE
2102
CSE
2102
Chapter 4 - SummaryChapter 4 - Summary Jump to OO Design Slides … Other Upcoming Topics Include:
Software Specification (Chapter 5) that Includes: Classic Techniques: Data-Flow Diagrams, Entity-
Relationship Diagrams, Finite State Machines, Petri-Nets, etc.
UML (Ghezzi and Web Page) Writing Specifications – What are They and What do
They Contain? Software Architectures Service-Oriented Architectures/Middleware