Title: Design
1Design
ECE 417/617Elements of Software Engineering
Stan Birchfield Clemson University
2From modeling to design
- Steps
- Analysis and modeling
- Design
- Construction (code generation and testing)
Design involves making the analysis model more
specific, to facilitate construction. Goal of
design is quality.
3FURPS
- Quality software is
- Functional capabilities of program
- Usable human factors, aesthetics
- Reliable frequency and severity of failure
- Performance response time, speed
- Supportable is the code maintainable,
extensible, testable, configurable, easy to
install, etc.
(Developed by Hewlett-Packard in 1980s)
4Basic design principles
- Design is iterative
- Architecture is refined over time by successively
filling in details - Refinement is a process of elaboration
- Results in hierarchical model
- A good design exhibits
- abstraction details are provided in lower
levels - modularity divide-and-conquer via smaller
independent components - refactoring internal structure of software is
improved without affecting external behavior
5Design model
- Design model has three aspects
- Architectural design
- Component-level (data) design
- Interface design
We will consider these in turn, with UI covered
in a separate lecture.
6Architectural Design
7Architectural design
- Architecture is a high-level representation of
the S/W with the major components identified - Architectural styles are templates, e.g.,
- Data-centered
- Data-flow
- Call and return
- Object-oriented
- Layered
- Architectural patterns define specific approach
for handling some behavioral characteristic of
system, e.g., - concurrency use O/S features or provide task
scheduler - persistence storage and retrieval of data
- distribution communication of components with
one another. Most common is broker acts as
middle man between client and server (CORBA).
Style is like Cape cod, A-frame. Pattern is
like kitchen.
8Architectural Styles
- Data-centered subsystems interact through
single repository - Model / View / Controller
- Call and return (Client / Server)
- Layered (three-tier, four-tier)
- Data-flow (pipe and filter)
9Layers and Partitions
- Layer group of related subsystems
- Layer knows about layers below it, but not layers
above it - Top layer no one else knows about it
- Closed architecture can only access layer
immediately below - Open architecture can access any layer below
- Partition peer subsystems, each with different
responsibilities
10Hierarchical decomposition
Level of abstraction
Example Open Systems Interconnection (OSI)
11Mapping DFD into architecture
- Transform mapping
- transform flow always exists represents
information flow within system incoming flow
passes through transform center, leads to
outgoing flow - To map DFD with transform flow characteristics
into specific architectural style, - review model
- refine models
- determine whether transform or transaction
characteristics - isolate transform center
- perform first and second level factoring
- refine
- Transaction mapping
- transaction flow occurs when one input gives rise
to several outputs transaction triggers data
flow along one of many paths - To map DFD with transaction flow characteristics,
- review model
- refine models
- determine whether transform or transaction
characteristics - isolate transaction center
- map to transform branch
- factor and refine
12Model / View / Controller (MVC)
- MVC
- Model subsystems maintain domain knowledge
- View subsystems display it to the user
- Controller subsystems manage sequence of
interactions with user - M doesnt depend upon V or C
- Changes propagated via subscribe/notify protocol,
using Observer design pattern - Well-suited for interactive systems
13MVC Details
14MVC Example
15MVC Example Details
2enterNewFileName(file,newName)
3setName(newName)
Controller
Model
1subscribeToFileEvents(file)
5getName()
InfoView
4notifySubscribedViews(file)
4notifySubscribedViews(file)
FolderView
1subscribeToFileEvents(file)
5getName()
16GUI-Based Programming
17Paradigms Compared
Application
callbacks
draw
output
Widgets
Application
output
input
input
The User
Traditional command-line
GUI-based
18Event/Message loop
19Event loop pseudocode
int main() return WinMain()
- WinMain()
- while (1) // loop forever, waiting for an
event - if (event_exists) //there is an event,
figure out what to do - if (event keydown_a) display(user
pressed the A key) - else if (event window_resize)
display(window resized) - else if (event repaint) display(need to
repaint window) - else if (event keydown_escape)
exit_program() -
-
20Event loop WinMain
int WINAPI WinMain (HINSTANCE hInst, HINSTANCE
hPrevInst, char cmdParam, int cmdShow)
char className "Winnie" WinClass
winClass (WindowProcedure, className, hInst)
winClass.Register () WinMaker win ("Hello
Windows!", className, hInst) win.Show
(cmdShow) MSG msg int status while
((status GetMessage ( msg, 0, 0, 0)) ! 0)
if (status -1) return -1
DispatchMessage ( msg) return
msg.wParam
21Event loop WindowProc
LRESULT CALLBACK WindowProcedure (HWND hwnd,
unsigned int message, WPARAM wParam, LPARAM
lParam) switch (message) case
WM_DESTROY PostQuitMessage (0) return 0
return DefWindowProc (hwnd, message,
wParam, lParam )
22Event loop (cont.)
- int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE
hprev, PSTR cmdline, int ishow) -
- HWND hwnd
- MSG msg
- //initialization code goes here
- while(1)
- // Get message(s) if there is one
- if(PeekMessage(msg,hwnd,0,0,PM_REMOVE))
- if(msg.message WM_QUIT)
- break
- TranslateMessage(msg)
- DispatchMessage(msg) //this calls the
CALLBACK function WinProc() - else
- DrawScene() //display the OpenGL/DirectX scene
-
-
23Event loop (cont.)
- LRESULT CALLBACK WinProc(HWND hwnd, UINT message,
WPARAM wparam, LPARAM lparam) -
- PAINTSTRUCT ps
- // Depending on the message -- we'll do
different stuff - switch(message)
- case WM_PAINT
- Draw()
- return 0
- // ESC will quit program
- case WM_KEYDOWN //user pressed a key
- if(GetAsyncKeyState(VK_ESCAPE)) //it was the
escape key - PostQuitMessage(0) //quit program
- return 0
- case WM_DESTROY //windows wants the
program to die - case WM_CLOSE //or the user closed the window
- PostQuitMessage(0) //quit program
- return 0
-
- return DefWindowProc(hwnd, message, wparam,
lparam)
24GUI Concepts
- Widget graphic object with functionality e.g.,
button, toolbar, ... - Window holds widgets
- Child/parent relationships between windows
- Event / message how windows communicate
25Anatomy of a Window
title bar
menu
toolbar
client area
status bar
26Microsoft Windows Programming
- History
- Win32 API core library written in C
- MFC C wrappers around most common Win32 API
functions - Lots of macros
- Lots of legacy code
- Not free, not portable
- But it works (generally speaking)
27Analyzing architectural designs
- Two approaches developed by SEI
- Architecture trade-off analysis method (ATAM)
- Collect scenarios and requirements
- Evaluate quality attributes and their sensitivity
- Critique candidate architectures
- Scenario-based architectural analysis (SAAM)
- Uses scenarios to analyze architectures with
respect to quality attributes
Quality attributes reliability, performance,
security, maintainability, flexibility,
testability, portability, reusability,
interoperability
28Component-level Design
29Component-level design
- Occurs after the first iteration of architectural
design - Goal translate the design model into
operational software - Component is set of collaborating classes
- Designing components
- OCL
- flow chart
- tabular design notation Decision table has four
quadrants specifying conditions and actions, as
well as rules for both - PDL (pseudocode)
30Decomposition
System
...
Subsystem1
SubsystemN
...
...
Class1a
Class1n
ClassNa
ClassNn
31Coupling and cohesion
- Coupling -- of dependencies between subsystems
- Cohesion -- of dependencies within subsystem
- Goal low coupling, high cohesion
- 7 /- 2 rule keep number of concepts at any
given layer of abstraction bounded
32Additional design principles
- Single responsibility (SRP)A class should have
only one reason to change - Open-closed (OCP) Software entities should be
open for extension but closed for modification
(achieved via inheritance) - Liskov substitution (LSP)Subclasses should be
substitutable for their base classes - Dependency inversion (DIP)Abstractions should
not depend upon details - Interface segregation (ISP)Many client-specific
interfaces are better than one general purpose
interface - Release reuse equivalency (REP)Granule of reuse
is granule of release - Common closure (CCP)Classes that change together
belong together - Common reuse (CRP)Classes in a package are
reused together
33Data structures and flow
- Software system is composed of
- data structures, and
- data flow
- Which is more important?
Show me your code and conceal your data
structures, and I shall continue to by
mystified. Show me your data structures and I
wont usually need your code. It will be
obvious. Fred Brooks
34What is a Design Pattern?
- A design pattern
- abstracts a recurring design structure
- comprises class and/or object
- dependencies,
- structures,
- interactions, or
- conventions
- distills design experience
35Re-use
- Code re-use
- Dont reinvent the wheel
- Requires clean, elegant, understandable, general,
stable code - leverage previous work
- Design re-use
- Dont reinvent the wheel
- Requires a precise understanding of common,
recurring designs - leverage previous work
36Some design patterns
- Abstract factory
- Adapter
- Bridge
- Command
- Composite
- Façade
- Subject / Observer
- Proxy
- Strategy
37Subject-observer
from Vlissides
38Subject-observer (cont.)
1
Subject Register(Observer) Unregister(Observer) N
otifyAll()
Observer OnUpdate()
for all o in observers o.OnUpdate()
39Subject-observer (cont.)
1
Subject Register(Observer) Unregister(Observer) N
otifyAll()
Observer virtual OnUpdate()
for all o in observers o.OnUpdate()
ConcreteSubject
ConcreteObserver virtual OnUpdate()
40Model / view / controller (MVC)
(displays data)
View
Model m Controller c(m) View v(c)
(mediates)
Controller
(holds data)
Model
calls Register()
Main
Create()
View
Create()
OnUpdate()
Register()
Create()
Set()
Controller
Set()
Model
41MVC (cont.)
1
Subject Register(Observer) Unregister(Observer) N
otifyAll()
Observer virtual OnUpdate()
for all o in observers o.OnUpdate()
Controller
View virtual OnUpdate()
42MVC (cont.)
class Observer protected virtual void
OnUpdate(MsgId message_id) 0 class
Subject public enum MsgId void
RegisterObserver(Observer obs) virtual void
NotifyAllObservers(MsgId message_id)
for (int i0 iltm_observers.size() i)
m_observersi-gtOnUpdate(message_id)
private stdvectorltObservergt
m_observers
43MVC (cont.)
class Controller public Subject
Controller(Data d) m_data(d) const
Data GetData() const void AddSphere(const
Sphere s) m_data-gtAddSphere(s)
NotifyAllObservers(ADD_SPHERE) private
Data m_data
44MVC (cont.)
class MainWnd public Observer, CWnd public
MainWnd(Controller c) m_controller(c)
c.Register(this) virtual void
OnUpdate(int message_id) switch
(message_id) case SubjectADD_SPHERE
... private
Controller m_controller
45Adapter
- You have
- legacy code
- current client
- Adapter changes interface of legacy code so
client can use it - Adapter fills the gap b/w two interfaces
- No changes needed for either
- legacy code, or
- client
46Adapter (cont.)
class NewTime public int GetTime()
return m_oldtime.get_time() 1000 8
private OldTime m_oldtime
47Command
- You have commands that need to be
- executed,
- undone, or
- queued
- Command design pattern separates
- Receiver from Invoker from Commands
- All commands derive from Command and implement
do(), undo(), and redo()
48Implementing Undo/Redo
- Multi-level undo/redo requires two classes
- Command
- CommandManager
class Command public virtual bool
Execute() 0 virtual bool Unexecute() 0
virtual Command()
class CommandManager private typedef
listltCommandgt CommandList CommandList
m_undoList CommandList m_redoList public
void DoCommand(Command com) void Undo()
void Redo()
http//www.codeproject.com/KB/cpp/undoredo_cpp.asp
x
49Facade
- You
- have a set of related classes
- want to shield the rest of the system from these
details - Facade provides a simplified interface
- Encapsulates a subsystem
50Composite
- You want uniformly to treat
- items (atomic elements), and
- groups (containing items or other groups)
- Composite interface specifies operations that are
shared between items and groups - Examples hierarchy of files and directories,
groups of drawable elements
51Composite (cont.)
Composite
Group
Item
52Proxy
- You want to
- delay expensive computations,
- use memory only when needed, or
- check access before loading an object into memory
- Proxy
- has same interface as Real object
- stores subset of attributes
- does lazy evaluation
53Strategy
- You want to
- use different algorithms depending upon the
context - avoid having to change the context or client
- Strategy
- decouples interface from implementation
- shields client from implementations
- Context is not aware which strategy is being
used Client configures the Context - strategies can be substituted at runtime
- example interface to wired and wireless networks
54Strategy (cont.)
Client
Policy
Strategy
Context
Concrete StrategyA
Concrete StrategyB
55Strategy (cont.)
Lots of switch statements is evidence of code
smell
Polymorphism, using strategy pattern, cleans this
up
http//codebetter.com/blogs/jeremy.miller/archive/
2006/04/11/142665.aspx
56Bridge
- You
- have several different implementations
- need to choose one, possibly at run time
- Bridge
- decouples interface from implementation
- shields client from implementations
- Abstraction creates and initializes the
ConcreteImplementations - Example stub code, slow code, optimized code
57Bridge (cont.)
Client
Implementor
Abstraction
Concrete ImplementorA
Concrete ImplementorB
Refined Abstraction
58Design pattern space
from Vlissides