Title: Object Design
1sysc-4800 Software Engineering
Part VI - Object Design
2Part VII - Object Design
- Overview
- Basic Concepts
- Solution domain classes
- Specifying exceptions
- Object design process
- Service specification
- Component selection (Reuse)
- Object model restructuring
- Object model optimization
- Process
3Goals (I)
- During Analysis, we describe the system in terms
of - external behavior (use cases),
- application domain concepts (class diagram),
- dynamic models (interaction diagrams),
- and non-functional requirements.
- During System Design, we describe the system in
terms of - sub-systems and deployment
- storage, access control, control flow strategies
- boundary conditions
- Object design is the process of
- refining the analysis model,
- refining the system design model,
- and making low-level design decisions
4Goals (II)
- The object designer must choose among different
ways to implement the analysis model with the
goal to - minimize execution time, memory and other
measures of cost, - improve maintainability, etc.
- It also aims at closing the gap between
off-the-shelf components (COTS) selected during
system design and application objects (e.g.,
adapter pattern) - Object Design serves as the basis of
implementation
5Closing the Gap
6Part VII - Object Design
- Overview
- Basic Concepts
- Solution domain classes
- Specifying exceptions
- Object design process
- Service specification
- Component selection (Reuse)
- Object model restructuring
- Object model optimization
- Process
7Solution Domain Classes
- During Analysis,
- entity objects are application (domain) objects,
- control and interface objects are solution
(domain) objects. - During system design,
- additional solution objects related to the
software and hardware platform are identified. - New solution objects are also identified during
object design - Use of Design patterns lead to new classes
- The implementation of algorithms may necessitate
objects to hold values - New low-level operations may be needed during the
decomposition of high-level operations
8The Open-Close Principle
- A class must be open and closed where
- open means it has the ability to be extended and
- closed means it cannot be modified other than by
extension. - The idea is that once a class has been approved
for use having gone through code reviews, unit
tests, and other qualifying procedures, you don't
want to change the class very much, just extend
it. - In practice the open/closed principle simply
means making good use of abstraction and
polymorphism.
9Example
- Assume this piece of class diagram
- Assume we want to change this first model to
permit overdrafts in some current accounts - It would not be correct to change the withdraw
operation in CurrentAccount as SavingsAccount
inherits it - Another solution would involve overridding
withdraw in SavingsAccount, but this would lead
to code replication - Yet another solution would involve adding run
time tests testing the instance type, but this
violates the closed principle. - Similar problems occur if member functions have
to be defined on CurrentAccount only (e.g.,
cashCheque).
10Run time tests testing the instance type
- public class CurrentAccount
- void withdraw(double amt)
- if (this instanceof SavingsAccount)
- // Check if becoming overdrawn
-
- balance - amt
-
-
- This implementation involves a reference to a
subclass, which means that superclass code has to
be changed if new subclasses are added - violates the closed principle.
11Example (cont.)
- The CurrentAccount class is performing two roles
- interfaces implemented by all account objects,
- default implementation of that interface.
- These roles conflict.
- Rule
- all superclasses should be abstract.
- the superclass operation can be called in the
subclass operation to make use of common
functionality
12Example (cont.)
13Part VII - Object Design
- Overview
- Basic Concepts
- Solution domain classes
- Specifying exceptions
- Object design process
- Service specification
- Component selection (Reuse)
- Object model restructuring
- Object model optimization
- Process
14Erroneous Situations
- A method often makes sense only in a subset of
its input domain - In this situation,we do not want methods to
return erroneous results, loop for ever - A robust program keeps behaving reasonably in the
presence of errors - Graceful degradation at worst, error message and
no damage to data
15Exception Handling
- Approach to convey information about unusual
situations - user error,
- hardware failure,
- software failure
- Be able to distinguish such situations
- Handling of these situations must be separated
from normal control flow - Exception A method terminates normally or
exceptionally - In Java, each exceptional termination correspond
to an exception type Convey information about
the problem
16Part VII - Object Design
- Overview
- Basic Concepts
- Solution domain classes
- Specifying exceptions
- Object design process
- Service specification with an example
- Component selection (Reuse)
- Object model restructuring
- Object model optimization
- Process
17Object Design Activities
- 1. Service specification
- Describes precisely each class interface, in
terms of the selected programming language
features and associated libraries - 2. Component selection (Reuse)
- Identify off-the-shelf components and additional
solution objects - 3. Object model restructuring
- Transforms the object design model to improve its
understandability and extensibility - Use design patterns
- 4. Object model optimization
- Transforms the object design model to address
performance criteria such as response time or
memory utilization. - Change algorithms, reduce multiplicities,
redundant associations, etc.
18Service Specification Goals
- Requirements analysis
- Identifies attributes and operations without
specifying their parameters or their types. - Object design
- Identify missing classes, attributes and
operations - Specify visibility information
- Specify type signature information
- Specify contracts (constraints)
- Specify exceptions
19JEWEL Map with political boundaries and emission
sources
Joint Environmental Workshop and Emission
Laboratory (JEWEL)
20JEWEL Subsystem decomposition
Displays geographical and emission data to the
user
Manages simulations and results
Engine for emission simulations
Manages geographical information for
Visualization and EmissionModeling (Geographical
Information System)
Maintains persistent data including GIS and
emissions data
21Subsystem description for the GIS of JEWEL.
- JEWEL GIS
- Purpose
- store and maintain the geographical information
for JEWEL - Service
- creation and deletion of geographical elements
(roads, rivers, lakes, and boundaries) - organization of elements into layers
- zooming (selection of points given a level of
detail) - clipping (selection of points given a bounding
box)
22GIS Object model
23Missing Classes, Attributes and Operations
- Clipping and Zooming services are not part of the
application domain but are rather related to the
user interface (solution domain) - Need to create a sequence diagram describing the
realization of the zoom operation - Clipping can be realized independently of the
kind of element being displayed (e.g., road,
river segments) - New class LayerElement (abstract) which provide
operations for all elements that are part of a
layer - e.g., highway, secondary road, river, lake,
state, county
24ZoomMap Use Case
- Entry Condition
- The map is displayed in a window, and at least
one layer is visible - Flow of Events
- The end user selects the zoom tool from the tool
bar. The system changes the cursor to a
magnifying glass. - The end user selects a point on the map using a
mouse by either clicking the left or the right
mouse button. The point selected by the user will
become the new center of the map. - The end user clicks the left mouse to request an
increase in the level of detail (I.e., zoom in)
or the right mouse button to request a decrease
of the level of detail (i.e., zoom out) - The system computes the new bounding box and
retrieves from the GIS the corresponding points
and lines from each visible layer - The system then displays each layer using a
predefined color in the new bounding box - Exit Condition
- The map is scrolled and scaled to the requested
position and detail level
25Sequence diagram for zoomIn()
26New Object Model Clipping
- Adding operations to the object model of the
JEWEL GIS to realize clipping - getOutline clipping the lines and polygons of
individual elements, given a bounding box (r) - getOutline in Layer is responsible for invoking
getOutline in LayerElement for each layer
element, and return all lines and polygons into a
single data structure (e.g., a vector) - Both operations return collections of lines and
polygons - The visualization subsystem will then translate
GIS coordinates into screen coordinates,
adjusting scale, scrolling, and drawing line
segments
27Zooming Problem
- getOutline requires a detail level to scale each
line and polygon and to reduce the number of
points for lower levels of details - e.g., when the user zooms out the map by a factor
of 2, GIS returns only half the number of points
for a given layer element
High detail
Low detail
Two crossingroads
Two neighboringcounties
28Additional Attributes and Methods
- LayerElement.getOutline() is not trivial
- Different LayerElements may share points
(connecting roads, neighboring counties). - The algorithm cannot select arbitrarily points
depending on the level of detail, disregarding
whether points are shared or not.
29Types and Signatures
30Factory Method
Design Pattern
- Intent Define an interface for creating an
object, but let subclasses decide which class to
instantiate. - Also known as virtual constructor
- Typical application contexts
- A class cant anticipate the class of objects it
must create - A class wants its subclasses to specify the
objects it creates - Classes delegate responsibility to one of several
helper subclasses, and you want to localize the
knowledge of which helper subclass is the
delegate.
31Factory Method Structure
Design Pattern
Product
productFactoryMethod()
ConcreteProduct
return new ConcreteProduct()
32Layer Factory
Layer label getOutline(bbox) addElement()
RoadLayer addElement() createHighway() createSecRo
ad()
WaterLayer addElement() createRiver() createLake()
PoliticalLayer addElement() createCounty() createS
tate()
Highway
State
River
Lake
SecondaryRoad
County
- Layer is the Creator and LayerElements are the
Product - addElement() is the factory method
- Road/Water/PoliticalLayer are the
ConcreteCreators - createHighway(), createRiver() are operations
that call the factory method to create the
ConcreteProducts (Highway/River/County) - LayerElement in turn is a Creator of
Polygon/Polylines - Connects to a parallel hierarchy of Shapes (not
shown), with subclasses (Highway, Lake) enforcing
the objects it creates.
33Alternative Solution OCL
Layer
label
getOutline(bbox)
RoadLayer
WaterLayer
PoliticalLayer
Highway
State
River
Lake
SecondaryRoad
County
context WaterLayer inv elements-gtforAll ( e
LayerElement e.oclIsTypeOf( River ) or
e.oclIsTypeOf( Lake ) )
34Flyweight Pattern
Design Pattern
- Intent Use sharing to support large number of
fine-grained objects efficiently. - Typical application contexts
- An application uses a large number of objects.
- Storage costs are high because of the sheer
quantity of objects. - Most object state can be made extrinsic
- Many groups of objects may be replaced by
relatively few shared objects once extrinsic
state is removed. - The application doesnt depend on object
identity. Since flyweight objects may be shared,
identity tests will return true for conceptually
distinct objects.
35Flyweight Structure
Design Pattern
Flyweight
operation(extrinsicState)
FlyweightFactory
getFlyweight(key)
if (flyweightkey exists) return existing
flyweight else create new flyweight add
it to pool of flyweights return new
flyweight
ConcreteFlyweight
UnsharedConcreteFlyweight
instrinsicState Operation(extrinsicState)
allState operation(extrinsicState)
Client
36Specifying Exceptions
- If a pre-condition is violated, an exception can
be raised - Exceptions can be identified by examining each
parameter and the states in which the method can
be invoked - Illegal values and combinations of values lead to
defining exceptions - e.g., bbox, detail parameters in
LayergetOutline() - Nonpositive values trigger exceptions
ZeroBoundingBox, ZeroDetail
37Example
ltltpreconditiongtgt bbox.widthgt0 and bbox.lengthgt0
ltltpreconditiongtgt detailgt0
ltltexceptiongtgt ZeroBoudingBox
ltltexceptiongtgt ZeroDetail
38Defensive Programming
- Defensive programming
- The callee verifies whether the precondition is
satisfied. - If so execution performs as normal thus
satisfying the postcondition. - Otherwise, an exception is raised.
- Design by contract
- It is up to the caller to ensure the precondition
for the method to execute properly is satisfied - Defensive programming entails effort and
execution overheads, but leads to more robust
systems - Program defenses can be disabled before delivery
if execution overhead is a problem but this
should be considered carefully.
39Part VII - Object Design
- Overview
- Basic Concepts
- Solution domain classes
- Specifying exceptions
- Object design process
- Service specification with an example
- Component selection (Reuse)
- Object model restructuring
- Object model optimization
- Process
40Goal Re-use
- Use and adapt off-the-shelf components that can
help us realize subsystems - Build versus buy trade-off
- Class Libraries
- Domain-independent classes perform basic tasks
(string,array,files) - Usually passive
- Components
- Self-contained blackbox with cohesive set of
services - Plug-in, either at source or binary level.
- Design Patterns
- Re-use of abstract designs involving collections
of cooperating classes - Encourage designs that anticipate change
- Frameworks
41Frameworks
- Definition
- Reusable partial application that can be
specialized to produce custom applications - Examples
- middleware frameworks Java RMI, CORBA
implementations - enterprise application frameworks Avionics,
telecommunications, enterprise business - infrastructure framework Communication tasks,
user interface design - Framework vs. libraries
- frameworks are targeted to particular
technologies (e.g., data processing, cellular
communications) or to application domains (e.g.,
user interface, real-time avionics) - are supposed (or need) to be refined
- Framework vs. design pattern
- Design patterns provide general solutions to
recurrent problems, not partial applications
42Component Selection
- Select existing off-the-shelf class libraries,
frameworks or components - DBMS,
- distribution middleware,
- application frameworks,
- GUI builders
- Adjust the class libraries, framework or
components - Change the API if you have the source code.
- Use the adapter or bridge pattern if you dont
have access
43Maximize Reuse
- Look for existing classes in class libraries
- Java Foundation Classes, ....
- Select data structures appropriate to the
algorithms - Container classes
- Arrays, lists, queues, stacks, sets, trees, ...
- Define new internal classes and operations only
if necessary - Complex operations defined in terms of
lower-level operations might need new classes and
operations
44Part VII - Object Design
- Overview
- Basic Concepts
- Solution domain classes
- Specifying exceptions
- Object design process
- Service specification with an example
- Component selection (Reuse)
- Object model restructuring
- Object model optimization
- Process
45Restructuring Goals
- Manipulate the models to meet design goals
- Transforming n-ary associations into binary
associations - Implementing associations as references
- Collapsing classes with no significant behavior
or attribute - Splitting complex classes
- Re-arranging classes and operations to increase
inheritance - Address maintainability, readability,
understandability
46 Implement Associations
- Strategy for implementing associations
- Be as uniform as possible across system
- Account for multiplicity and direction of
association - Example of uniform implementation
- 1-to-1 association
- Role names are treated like attributes in the
classes and translate to references - 1-to-many association
- Translate to Vector (when ordered)
- Qualified association
- Translate to Hash table
- Association classes
47Unidirectional 1-to-1 Association
Object design model before transformation
1
1
Object design model after transformation
48Bidirectional 1-to-1 Association
Object design model before transformation
1
1
Object design model after transformation
MapArea
-zoomInZoomInAction
getZoomInAction()ZoomInAction setZoomInAction(z
ZoomInAction)
49Java Code
- class MapArea extends JPanel
- private ZoomInAction zoomIn
- / Other methods omitted /
- void setZoomInAction (ZoomInAction action)
- if (zoomIn ! action)
- zoomIn action
- zoomIn.setTargetMap(this)
-
-
-
- class ZoomInAction extends AbstractAction
- private MapArea targetMap
- / Other methods omitted /
- void setTargetMap(MapArea map)
- if (targetMap ! map)
- targetMap map
- targetMap.setZoomInAction(this)
-
-
501-to-Many Association
Object design model before transformation
1
Object design model after transformation
51Many-to-Many Association
Object design model before transformation
ordered
Object design model after transformation
52Association Classes
Object design model before transformation
Object design model after transformation
53Qualification
Object design model before transformation
simName
0..1
Object design model after transformation
54Increase Reuse
- Object design is the last opportunity to revisit
and refine inheritance hierarchies, at a
reasonable cost - Inheritance allows developers to reuse code
across similar classes - Rearrange and adjust classes and operations to
prepare for inheritance - Abstract common behavior out of groups of classes
- If a set of operations or attributes are repeated
in 2 classes the classes might be special
instances of a more general class.
55Building a super class from several classes
- Prepare for inheritance. All operations must have
the same signature but often the signatures do
not match - Some operations have fewer arguments than others
- Use overloading (Possible in Java)
- Similar attributes in the classes have different
names - Rename attribute and change all the operations.
- Operations defined in one class but not in the
other - Use virtual functions and class function
overriding. - Abstract out the common behavior (set of
operations with same signature) and create a
super-class out of it. - Well-designed inheritance hierarchies are
desirable.
56Operations with fewer arguments
Object design model before transformation
Object design model after transformation
m(p1, p2) calls m(p1)
57Operations defined in one class but not in the
other
Object design model before transformation
Object design model after transformation
c2m2() empty or throws an exception or client
code checks type of instance (not recommended)
58Part VII - Object Design
- Overview
- Basic Concepts
- Solution domain classes
- Specifying exceptions
- Object design process
- Service specification with an example
- Component selection (Reuse)
- Object model restructuring
- Object model optimization
- Process
59Optimization Goals
- Address performance requirements of the system
- The analysis model is semantically correct but
often too inefficient if directly implemented. - Changing algorithms
- Reducing multiplicities of associations
- Add redundant associations
- Caching or delaying complex computations
- Adding access to lower layers (opening up the
architecture) - As a designer you must strike a balance between
efficiency and clarity.
60Revisiting Access Paths
- For each operation
- What are the most frequent operations? ( e.g.,
Sensor data lookup) - What associations do they have to traverse?
- Add redundant associations if necessary
- For each association
- Is the many multiplicity really necessary
- Is the many side involved in a frequent search
- In this case, consider reducing to one (e.g.,
qualifier) - Otherwise, consider ordering ( ordered )
- For each attribute
- What operations use the attribute?
- Are get() and set() the only operations accessing
it? - Does the attribute really belong to this object
or should it be moved to calling object?
61Redundant Associations
- Problem Sequence diagrams show that associations
between Class 1 and Class 3 are frequently
navigated, at a high performance cost
- Should we add this association?
- If we do, we have to manage consistency
- Trade-off performance in navigation versus
system state changes
62Turning Objects into Attributes
- During analysis, many domain classes are
identified - During design, many of them will turn out to
contain little behavior and few attributes they
can sometimes be collapsed into an attribute - Reduce complexity of the object model
- The decision of collapsing classes and one should
make sure that all the behaviors associated with
each class have been identified, i.e., object
design is complete
63SocialSecurity Example
64Caching Expensive Computations
- Expensive computations should be done once
- Define private attributes or new classes to store
derived attributes information locally (cache) - Problem with caching derived attributes
- Derived attributes must be updated when base
values change. - There are 3 ways to deal with the update
problem - Explicit code
- Implementor determines affected derived
attributes - Periodic computation
- Re-compute derived attribute occasionally
- Active value
- An attribute can designate set of dependent
values which are automatically updated when
active value is changed (notification, data
trigger) - Trade-off average response time improved, but
consume memory space
65JEWEL LayergetOutline()
- Let us assume that the vector of Points returned
is always the same for a given detail and bbox - Tendency to focus on a limited number of points
around a specific city or region - Private cachedPoints attribute which remember the
result of getOutline() for a given bbox and
detail pair - LayergetOutline() check cachedPoints first and,
if not found, invokes getOutline() in each
contained LayerElement - Tradeoff response time vs. memory
66Delaying Complex Computations
67Part VII - Object Design
- Overview
- Basic Concepts
- Solution domain classes
- Specifying exceptions
- Object design process
- Service specification with an example
- Component selection (Reuse)
- Object model restructuring
- Object model optimization
- Process
68Object Design Document
- Introduction
- 1.1 Object design trade-offs
- 1.2 Interface documentation guidelines
- 1.3 Definitions, acronyms, and abbreviations
- 1.4 References
- Packages
- Class Interfaces
- Glossary
69Object Design Process
70Object Design Process II
- Fundamental Issue
- Maintain consistency between object design and
code - Current tools do not support 2-way traceability
and automated change between analysis and code - Analysis and Design models tend to fall behind
71Javadoc Tagged Comments
- / The class Layer is a container of
LayerElements, each representing a polygon or - a polyline. For example, JEWEL typically has a
road layer, a water layer, a - political layer, and an emissions layer.
- _at_author John Smith
- _at_version 0.1
- _at_see LayerElement
- _at_see Point
- /
- class Layer
- / Member variables, constructors, and other
methods omitted / - Enumeration elements()
- / The getOutline operation returns an
enumeration of points representing the - layer elements at a specified detail level.
The operation only returns points - contained within the rectangle bbox.
- _at_param box The clipping rectangle in
universal coordinates - _at_param detail Detail level (big numbers mean
more detail) - _at_return A enumeration of points in
universal coordinates. - _at_throws ZeroDetail
- _at_throws ZeroBoundingBox
72Summary
- Object design closes the gap between the analysis
model and the machine. - Object design is the process of adding details to
the analysis model by making implementation
decisions - Object design includes
- 1. Service specification
- 2. Component selection
- 3. Object model restructuring
- 4. Object model optimization
- Object design is documented in the Object Design
Document, which can be generated using tools such
as JavaDoc.