Title: COS 315
1COS 315 SOFTWARE ENGINEERING 13. Object
Design Adding detail to the object model. Serves
as the basis for implementation
2Modeling Heuristics
- Modeling must address our mental limitations (!)
- Our short-term memory has only limited capacity
(72) - Good Models deal with this limitation, because
they - Do not tax the mind
- A good model requires only a minimal mental
effort to understand - Reduce complexity
- Turn complex tasks into easy ones (by good choice
of representation) - Use abstractions
- Have organizational structure
- Memory limitations are overcome with an
appropriate representation (natural model)
3Object Design Low-level Design
- Object design is the process of adding details to
the requirements analysis models and making
implementation decisions. - The software designer must choose among different
ways to implement the analysis models (with the
goal of minimizing execution time, memory and
other measures of performance). - Requirements Analysis The analysis models
deliver operations for the object model. - Object Design Now we iterate on (refine, add
more detail to) these operations. - Detailed object design serves as the basis of
implementation
4State of the Art of Model-based Software
Engineering
- The Vision
- During object design, we would like to implement
a system that realizes the use cases specified
during requirements elicitation and system
design. - The Reality
- Different developers usually handle contract
violations differently. - Undocumented parameters are often added to the
API to address a requirement change. - Additional attributes are usually added to the
object model, but are not handled by the
persistent data management system, possibly
because of a miscommunication. - Many improvised code changes and workarounds that
eventually yield to the degradation of the system.
5Object Design Issues Issues to face in object
design - Full definition of associations
between classes - Full definition of
classes - Choice of algorithms and data
structures - Inheritance (both Generalization
and Specialization) and other - Decision
on control - Packaging
6Characteristics of Object Design Activities
- Developers perform transformations to the object
model to improve its modularity and performance. - Developers transform the associations of the
object model into collections of object
references, because programming languages do not
support the concept of association. - If the programming language does not support
contracts, the developer needs to write code for
detecting and handling contract violations. - Developers often revise the interface
specification to accommodate new requirements
from the client. - All these activities are not intellectually
challenging - They have a repetitive and mechanical flavour
that makes them error prone.
7Object design is not sequential process
Object Design Activities
- Object design includes four groups of activities
- 1. Service specification (i.e. what operations
are public) - Describe precisely each class interface
- 2. Component selection
- Identify off-the-shelf components, e.g. class
libraries, etc. to use if possible ? reuse - 3. Object model restructuring
- Transform the object design model to improve its
understandability and extensibility ? design
patterns - 4. Object model optimization
- Transform the object design model to address
performance criteria such as response time or
memory utilization.
81. Service Specification
- In requirements analysis,
- we identified attributes and operations of
objects without specifying their types or their
parameters. - But, in object design, now we must
- add visibility information
- add type signature information
- add contracts
9Adding Visibility
- UML defines three levels of visibility
- Private
- A private attribute can be accessed only by the
class in which it is defined. - A private operation can be invoked only by the
class in which it is defined. - Private attributes and operations cannot be
accessed by any subclasses or other classes. - Protected
- A protected attribute or operation can be
accessed by the class in which it is defined and
by any descendant of that class. - Public
- A public attribute or operation can be accessed
by any class.
10Visibility in UML is denoted by prefixing the
symbol - for private for protected
for public to the name of the attribute or the
operation in the class diagram E.g.
Hashtable
Attribute is private
-numElementsint
put()
get()
All operations are public
remove()
containsKey()
size()
11Example - Implementation of UML Visibility in Java
- public class Tournament
- private int maxNumPlayers
-
public Tournament(League l, int
maxNumPlayers) public int getMaxNumPlayers()
public List getPlayers() public void
acceptPlayer(Player p) public void
removePlayer(Player p) public boolean
isPlayerAccepted(Player p)
12Information Hiding Heuristics
- Build firewalls around classes
- Carefully define public interfaces for classes as
well as subsystems. - Apply the Need to Know principle. The less any
class or subsystem needs to know about any other
class or subsystem then - the less likely any class will be affected by
changes to any other class. - the easier a class can be changed
- But there is a trade-off
- Information hiding versus efficiency
13Information Hiding Design Principles
- Only the operations of a class are allowed to
manipulate its attributes - Other classes access attributes only via public
operations set and get . - Hide external objects at subsystem boundary
- Define abstract class interfaces which mediate
between system and external world as well as
between subsystems - Do not apply an operation to the result of
another operation - Write a new operation that combines the two
operations.
14Add Type Signature Information
The type of an attribute specifies range
of allowed values. The type of a
parameter constrains the range of values the
parameter or return value can take.
Hashtable
-numElements
put()
get()
remove()
containsKey()
size()
Signature
Hashtable
-numElementsint
put(keyObject,entryObject)
get(keyObject)Object
remove(keyObject)
containsKey(keyObject)boolean
size()int
15Services Among Objects
- When objects collaborate, one object typically
provides a service to another. - Examples
- A Client object might ask a Campaign object for
its details - The same Client object might then ask a boundary
object to display its related Campaign details to
the user
16Contracts an Approach to Defining Services
- A service can be defined as a contract between
the participating objects. - Contracts focus on inputs and outputs.
- Intervening process is seen as a black box.
- Irrelevant details are hidden.
- This emphasizes service delivery, and ignores
implementation.
17Contract-Style Operation Specification
- Intent or purpose of the operation
- Operation signature, including return type
- Description of the logic
- Other operations called
- Events transmitted to other objects
- Any attributes set
- Response to exceptions (e.g. an invalid
parameter) - Non-functional requirements
18Contracts
- Contracts for a class enable the caller and
callee to share the same assumptions about the
class. - Contracts include three types of constraints
- Invariant Something that is always true for all
instances of a class. Invariants are constraints
associated with classes or interfaces. Invariants
are used to specify consistency constraints among
class attributes. - Precondition Something that must be true before
an operation is invoked. Preconditions are
associated with a specific operation.
Preconditions are used to specify constraints
that a caller must meet before calling an
operation. - Postcondition Something that must be true after
an operation is invoked. Postconditions are
associated with a specific operation.
Postconditions are used to specify constraints
that must hold after the invocation of the
operation.
19Expressing constraints in UML
- OCL (Object Constraint Language) part of UML
- OCL allows constraints to be formally specified
on single model elements or groups of model
elements. - A constraint is expressed as an OCL expression
returning the value true or false. - OCL is not a procedural language (cannot
constrain control flow).
20Example
- OCL expressions for Hashtable operation put()
creates entry in hash table, associating a key
with value. - Invariant
- context Hashtable inv numElements gt 0
- Precondition
- context Hashtableput(key, entry)
pre!containsKey(key) - Postcondition
- context Hashtableput(key, entry) post
containsKey(key) and get(key) entry
OCL expression
Context is a class
Context is a class operation put
OCL expression
21Object Constraint Language
- Most OCL statements consist of
- Context, Property and Operation
- Context
- Defines domain within which expression is valid
- Instance of a type, e.g. object in class diagram
- Link (association instance) may be a context
- A property of that instance
- Often an attribute, association-end or query
operation
22- OCL operation is applied to the property
- Operations include
- Arithmetical operators , , - and /
- Set operators such as size, isEmpty and select
- Type operators such as oclIsTypeOf
23OCL Used for Pre- and Post-conditionsExample
- context CreativeStaffchangeGrade
- (gradeGrade, gradeChangeDateDate)
- pre
- grade oclIsTypeOf(Grade)
- gradeChangeDate gt today
- post
- staffGradegrade-gtexists
- staffGradeprevious-gtnotEmpty
- staffGrade.gradeStartDate gradeChangeDate
- staffGrade.previous.gradeFinishDate
gradeChangeDate
24Expressing Constraints in UML
- A constraint can also be depicted as a note
attached to the constrained UML element (e.g.
class) by a dependency relationship.
ltltinvariantgtgt
numElements gt 0
HashTable
ltltpreconditiongtgt
ltltpostconditiongtgt
numElementsint
!containsKey(key)
get(key) entry
put(key,entryObject)
get(key)Object
ltltpreconditiongtgt
remove(keyObject)
containsKey(key)
containsKey(keyObject)boolean
size()int
ltltpreconditiongtgt
ltltpostconditiongtgt
containsKey(key)
!containsKey(key)
25Constraints can involve more than one class
How do we specify constraints on more than one
class?
263 Types of Navigation through a Class Diagram
1. Local attribute
2. Directly related class
3. Indirectly related class
Player
Any OCL constraint for any class diagram can be
built using only a combination of these three
navigation types!
27Example
28Model Refinement with 3 additional Constraints
- A Tournaments planned duration must be under one
week. - Players can be accepted in a Tournament only if
they are already registered with the
corresponding League. - The number of active Players in a League are
those that have taken part in at least one
Tournament of the League.
29Specifying the Model Constraints
- Local attribute navigation
- context Tournament inv
- end - start lt Calendar.WEEK
- Directly related class navigation
- context TournamentacceptPlayer(p) pre
- league.players-gtincludes(p)
30- Indirectly related class navigation
- context LeaguegetActivePlayers post
- result tournaments.players -gt asSet
312. Component Selection
- Select existing off-the-shelf components
- Customize - adjust the components if available.
- Change the API if you have the source code.
- Use the adapter or bridge pattern if you dont
have access to source code. (See later!) - Otherwise design custom components.
Note Component - a physical and replaceable part
of the system that complies to an interface.
Examples include class libraries and
frameworks. Note (Application) Framework - a
set of classes providing a general solution that
can be refined to provide an application or
subsystem - a reusable (perhaps partial)
application targeted to particular technologies
or application domains.
32Class Libraries and Frameworks
- Class Libraries
- Less domain specific
- Provide a smaller scope of reuse.
- Class libraries are passive no constraint on
control flow. - Framework
- Classes cooperate for a family of related
applications. - Frameworks are active affect the flow of
control. - In practice, developers often use both
- Frameworks often use class libraries internally
to simplify the development of the framework. - Framework event handlers use class libraries to
perform basic tasks (e.g. string processing, file
management, numerical analysis. )
33Reuse ...
- Look for existing classes in class libraries.
- Select data structures appropriate to the
algorithms - Container classes - dynamically expandable data
structures - 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
343. Restructuring Activities
- Concerned with
- Realizing associations
- Associations - links between two or more objects.
Implement using references - one object stores
a handle or reference to another. - We realize logical associations in terms of
object references. - Revisiting inheritance to increase reuse
- Revising inheritance to remove implementation
dependencies
35Reuse
- Main goal
- Reuse knowledge from previous experience to
current problem. - Reuse functionality already available.
- Composition/Aggregation
- New functionality is obtained by aggregation.
- The new object with more functionality is an
aggregation of existing components. - Inheritance
- New functionality is obtained by inheritance.
- Three ways to get new functionality
- Implementation inheritance
- Specification/Interface inheritance
- Delegation (? composition/aggregation)
36Inheritance is found either by specialization or
generalization
37Increase Inheritance
- Rearrange and adjust classes and operations to
prepare for inheritance - Generalization The abstraction of common
features among classes by the creation of a
hierarchy of more general superclasses that
encapsulate the common features. - Start with classes and create superclass.
- Specialization a class has a set of features
that uniquely distinguish it from other classes.
Distinguishes subclasses from superclasses. - Start with base class and then create subclass.
- Generalization is a common modeling activity.
Extract common behaviour from groups of classes - If a set of operations or attributes are repeated
in two classes, the classes might be special
instances of a more general class. - Be prepared to change a subsystem (collection of
classes) into a superclass in an inheritance
hierarchy.
38Example Class Generalization Refactoring
Example Pull Up Field
Object design model before transformation
Object design model after transformation
39Generalization Example
public class Player private String
email //... public class Agent private
String eMail //... public class Advertiser
private String email_address //...
public class User private String
email public class Player extends User
//... public class Agent extends User
//... public class Advertiser extends User
//...
40Refactoring Example Pull Up Constructor Body
public class User public User(String email)
this.email email public class Player
extends User public Player(String email)
super(email) public class LeagueOwner
extends User public LeagueOwner(String email)
super(email) public class Advertiser
extends User public Advertiser(String email)
super(email)
public class User private String
email public class Player extends User
public Player(String email) this.email
email public class LeagueOwner extends
User public LeagueOwner(String email)
this.email email public class
Advertiser extendsUser public Advertiser(String
email) this.email email
41Building a superclass from several classes
- Prepare or modify classes for inheritance.
- All operations must have the same signature but
often the signatures do not match. - Some problems
- Some operations may have fewer arguments than
others Use overloading - 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 - Extract the common behaviour (set of operations
with same signature) and create a superclass out
of it. - Superclasses are desirable.
- increase modularity, extensibility and
reusability
42But beware of using inheritance too much,
especially when it is not really needed. Many
experts/gurus on OO design say prefer
composition/aggregation. Inheritance should only
be used when you can honestly say that a MyClass
object is a Superclass object Good class
Secretary extends Employee Bad class Secretary
extends AccountingSystem
43Implementation Inheritance
- A very similar class is already implemented that
does almost the same as the desired class
implementation.
List
Add()
- Example I have a List class, but I need a Stack
class. - How about subclassing the Stack class from the
List class and providing three methods, Push(),
Pop() and Top()?
Already implemented
Remove()
Stack
Push()
Pop()
Top()
- Problem with implementation inheritance
- Some of the inherited operations might exhibit
unwanted behavior. What happens if the Stack user
calls Remove() instead of Pop() ?
44Implementation Inheritance versus Interface
Inheritance
- Implementation inheritance
- Also called class inheritance
- Goal Extend an applications functionality by
reusing functionality in parent class - Inherit from an existing class with some or all
operations already implemented - Specification/Interface inheritance
- Also called subtyping
- Inherit from an abstract class with all
operations specified, but not yet implemented
45Delegation as alternative to Implementation
Inheritance
- Delegation is a way of making composition (or
aggregation) as powerful for reuse as
inheritance. - In Delegation, two objects are involved in
handling a request - A receiving object delegates operations to its
delegate. - The developer can make sure that the receiving
object does not allow the client to misuse the
delegate object
Delegate
Receiver
Client
Delegates to
calls
46Delegation instead of Implementation Inheritance
- Inheritance Extending a base class by a new
operation or overwriting an operation. - Delegation Catching an operation and sending it
to another object. - Which of the following models is better for
implementing a stack?
List
Stack
Add()
List
Remove()
Remove()
Push() Pop() Top()
Add()
Stack
Push() Pop() Top()
47Comparison Delegation versus Implementation
Inheritance
- Delegation
- For
- Flexibility Any object can be replaced at run
time by another one (as long as it has the same
type) - Against
- Inefficiency Objects are encapsulated.
48- Inheritance
- For
- Straightforward to use
- Supported by many programming languages
- Easy to implement new functionality
- Against
- Inheritance exposes a subclass to the details of
its parent class - Any change in the parent class implementation
forces the subclass to change (which requires
recompilation of both)
49Lecture on Design Patterns
- Many design patterns use a combination of
inheritance and delegation
50Implement Associations
- Strategy for implementing associations
- Be as uniform as possible
- Make individual decision for each association
- Example of uniform implementation
- 1-to-1 association
- Role names are treated like attributes in the
classes and translated to references - 1-to-many association
- Translated to some Vector type
51Designing Associations
- An association that has to support message
passing in both directions is a two-way
association. - A two-way association is indicated with
arrowheads at both ends. - Minimizing the number of two-way associations
keeps the coupling between objects as low as
possible
52Fragment of class diagram for the Agate case study
53Unidirectional 1-to-1 Association - Example
Association role targetMap is transformed into an
attribute in class ZoomInAction named targetMap
of type MapArea. Creating the association is then
just setting targetMap to refer to the correct
MapArea object.
Object design model before
transformation
targetMap
Object design model after transformation
targetMapMapArea
54Arrowhead shows the direction in which messages
can be sent.
1
1
carObjectId is placed in the Owner class
One-way one-to-one association
55Realization of a unidirectional, one-to-one
association
Object design model before transformation
1
1
Account
Advertiser
Source code after transformation
public class Advertiser private Account
account public Advertiser() account new
Account() public Account getAccount()
return account
56Bidirectional 1-to-1 Association - Example
zoomIn attribute added to class MapArea. To
ensure consistency, both objects refer to each
other - change visibility of attributes to
private and add methods to each class to access
and modify them. E.g. setZoomInAction sets the
zoomIn attribute and invokes setTargetMap to
change its targetMap attribute.
targetMap
zoomIn
2
4
1
3
57Bidirectional one-to-one association
Object design model before transformation
1
1
Advertiser
Account
Source code after transformation
public class Advertiser / The account field
is initialized in the constructor and never
modified. / private Account account public
Advertiser() account new Account(this)
public Account getAccount() return
account
public class Account / The owner field is
initialized in the constructor and never
modified. / private Advertiser owner public
Account(ownerAdvertiser) this.owner
owner public Advertiser getOwner()
return owner
581-to-Many Association
The many association must be realized via a
collection of references, e.g. Vector data
type. The attribute layerElements is implemented
as a Vector of references to individual
LayerElements.
Object design model before
transformation
Layer
LayerElement
1
Object design model after transformation
Layer
LayerElement
-containedInLayer
-layerElementsVector
elements()
getLayer()
addElement(le)
setLayer(l)
removeElement(le)
A many-to-many association may be implemented as
collections of references in both end classes.
59One-to-many association using a separate
collection class.
60Bidirectional, one-to-many association
Object design model before transformation
1
Advertiser
Account
Source code after transformation
public class Advertiser private Set
accounts public Advertiser() accounts new
HashSet() public void addAccount(Account a)
accounts.add(a) a.setOwner(this)
public void removeAccount(Account a)
accounts.remove(a) a.setOwner(null)
public class Account private Advertiser
owner public void setOwner(Advertiser newOwner)
if (owner ! newOwner) Advertiser old
owner owner newOwner if (newOwner !
null) newOwner.addAccount(this) if
(oldOwner ! null) old.removeAccount(this)
61Many-to-many associations using separate
collection classes.
62Bidirectional, many-to-many association
Object design model before transformation
ordered
Tournament
Player
Source code after transformation
public class Tournament private List
players public Tournament() players new
ArrayList() public void addPlayer(Player p)
if (!players.contains(p)) players.add(p)
p.addTournament(this)
public class Player private List
tournaments public Player() tournaments
new ArrayList() public void
addTournament(Tournament t) if
(!tournaments.contains(t)) tournaments.add(t)
t.addPlayer(this)
63Exceptions as building blocks for contract
violations
- Many object-oriented languages, including C and
Java do not include built-in support for
contracts. - However, we can use their exception mechanisms as
building blocks for signaling and handling
contract violations - In C and Java may use the try-throw-catch
mechanism - Example
- Let us assume the acceptPlayer() operation of
TournamentControl is invoked with a player who is
already part of the Tournament. - In this case acceptPlayer() should throw an
exception of type KnownPlayer.
64The try-throw-catch Mechanism in Java
- public class TournamentControl
- private Tournament tournament
- public void addPlayer(Player p) throws
KnownPlayerException - if (tournament.isPlayerAccepted(p))
- throw new KnownPlayerException(p)
-
- //... Normal addPlayer behavior
-
-
- public class TournamentForm
- private TournamentControl control
- private ArrayList players
- public void processPlayerApplications() // Go
through all the players for (Iteration i
players.iterator() i.hasNext()) - try // Delegate to the control
object. - control.acceptPlayer((Player)i.next())
- catch (KnownPlayerException e)
- // If an exception was caught, log it to
the console - ErrorConsole.log(e.getMessage())
-
65Implementing a contract
- For each operation in the contract, do the
following - Check precondition Check the precondition before
the beginning of the method with a test that
raises an exception if the precondition is false.
- Check postcondition Check the postcondition at
the end of the method and raise an exception if
the contract is violated. If more than one
postcondition is not satisfied, raise an
exception only for the first violation. - Check invariant Check invariants at the same
time as postconditions. - Deal with inheritance Encapsulate the checking
code for preconditions and postconditions into
separate methods that can be called from
subclasses.
66A complete implementation of the
Tournament.addPlayer() contract
invariant
getMaxNumPlayers() gt 0
preconditiongetNumPlayers() ltgetMaxNumPlayers(
)
67Heuristics for Mapping Contracts to Exceptions
- Be pragmatic, if you do not have enough time.
- Omit checking code for postconditions and
invariants. - Usually redundant with the code accomplishing
the functionality of the class - Not likely to detect many bugs unless written by
a separate tester. - Omit the checking code for private and protected
methods. - Focus on components with the longest life
- Focus on Entity objects, not on boundary objects
associated with the user interface. - Reuse constraint checking code.
- Many operations have similar preconditions.
- Encapsulate constraint checking code into methods
so that they can share the same exception classes.
68Mapping an object model to a relational database
- Persistent Objects
- UML object models can be mapped to relational
databases - Some degradation occurs because all UML
constructs must be mapped to a single relational
database construct - the table. - UML mappings
- A class is mapped to a table
- Each class attribute is mapped onto a column in
the table - An instance of a class represents a row in the
table - A many-to-many association is mapped into its own
table - A one-to-many association is implemented as
buried foreign key - Methods are not mapped
69 Mapping Object Models to DatabaseMapping the
User class to a database table
Map class attributes to table with same name.
User
firstNameString
loginString
emailString
User table
firstNametext25
logintext8
emailtext32
idlong
Introduced an arbitrarily unique id as a primary
key.
70Mapping Associations
- Associations with multiplicity one can be
implemented using a foreign key in one of the
entity tables to refer to another table. - For one-to-many associations, add a foreign key
to the table representing the class on the many
end. - For all other associations can select either
class at the end of the association.
71Mapping Associations
- Associations with multiplicity one can be
implemented using a foreign key. Because the
association vanishes in the table, call this a
buried association.
- For one-to-many associations add the foreign key
to the table representing the class on the many
end.
- For all other associations can select either
class at the end of the association.
1
LeagueOwner
League
72Another Example for Buried Association
Portfolio portfolioID ...
Foreign Key
Portfolio Table
Transaction Table
transactionID
portfolioID
73Mapping Many-To-Many Associations
In this case need a separate table for the
association
Separate table for Serves association
Primary Key
Airport Table
City Table
airportCode IAH HOU ALB MUC HAM
airportName Intercontinental Hobby Albany
County Munich Airport Hamburg Airport
cityName Houston Albany Munich Hamburg
74Mapping the Tournament/Player association as a
separate table
Player
Tournament
Tournament table
Player table
TournamentPlayerAssociation table
...
...
id
name
id
name
23
no
vice
56
alice
tournament
player
24
expert
79
john
23
56
23
79
75Realizing Inheritance
- Relational databases do not support inheritance.
-
- Two possibilities to map UML inheritance
relationships to a database schema - With separate tables (vertical mapping)
- The attributes of the superclass and the
subclasses are mapped to different tables. - By duplicating columns (horizontal mapping)
- There is no table for the superclass
- Each subclass is mapped to a table containing the
attributes of the subclass and the attributes of
the superclass
76Realizing inheritance with a separate table
User table
id
name
...
r
ole
Elena
56
LeagueOwner
Ivan
79
Pla
y
er
77Realizing inheritance by duplicating columns
User
name
LeagueOwner
Player
maxNumLeagues
credits
LeagueOwner table
Player table
id
...
id
...
maxNumLeagues
name
credits
name
Elena
56
12
79
126
Ivan
784. Design Optimizations
- Design optimizations are an important part of the
object design phase - The requirements analysis model is semantically
correct but often too inefficient if directly
implemented. - Optimization activities during object design
- 1. Add redundant associations to optimize access
paths - 2. Rearrange computations for greater efficiency
- 3. Store derived attributes to save computation
time - As an object designer, you must strike a balance
between efficiency and clarity. - Since optimizations may make your models more
obscure
79Design Optimization Activities
- Add redundant associations (Data flow
optimization) - 2. Rearrange execution order (Control flow
optimization) - 3. Turn classes into attributes (Object
optimization)
80Implement Application Domain Classes
- To collapse or not to collapse attribute or
association? - Object design choices
- Implement entity as embedded attribute, or
- Implement entity as separate class with
associations to other classes - Associations are more flexible than attributes
but often introduce unnecessary indirection.
81Optimization Activities Collapsing Classes
E.g. two classes may be collapsed into one.
82To Collapse or not to Collapse?
- Collapse a class into an attribute if the only
operations defined on the attributes are Set()
and Get()
83Optimization Activities Delaying Complex
Computations
Image
Real image expensive to load from file many
pixels. But real image need not be loaded until
image is displayed, i.e. paint() is called
filenameString
databyte
width()
height()
paint()
Design pattern
Use Proxy pattern
Calling classes access image via the Image
interface.
Image
filenameString
width()
height()
paint()
Complex operations on real image
Simple operations on proxy image
image
RealImage
ImageProxy
1
0..1
databyte
filenameString
width()
width()
height()
height()
paint()
paint()
84New Classes?
- New objects are often needed during object design
- Use of design patterns leads 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. - E.g. An EraseArea() operation offered by a
drawing program. - Conceptually very simple
- But implementation may require new helper
classes - E.g. Area is represented by array of pixels
- Repair() cleans up objects that were partially
covered by the erased area - Redraw() draws objects uncovered by the erasure
- Draw() erases pixels in background color not
covered by other objects
85Types of Logic Specification
Operation Specification Specification of Methods
- Logic description is probably the most important
element. - Two main categories
- Algorithmic types are white box they focus on
how the operation might work. - Non-algorithmic types are black box they
focus on what the operation should achieve.
86Non-Algorithmic Techniques
- Appropriate where correct result matters more
than method to arrive at it. - Decision tree complex decisions, multiple
criteria and steps . - Decision table similar applications to decision
tree. - Pre- and Post-condition pairs suitable where
precise logic is unimportant or uncertain.
87Example Decision Table
Conditions and actions
Rule 1
Rule 2
Rule 3
Conditions
Â
Â
Â
Actions
Â
Â
Â
Â
Â
No action
X
Send letter
Â
X
X
Set up meeting
Â
Â
X
88Algorithmic Techniques
- Suitable where users understand the procedure for
arriving at a result. - Can be constructed top-down, to handle
arbitrarily complex functionality. - Examples
- Structured English, Pseudo-Code
- Activity Diagrams
89Structured English
- Commonly used, easy to learn mix of everyday
language and programming language - Three types of control structure, derived from
structured programming - Sequences of instructions
- Selection of alternative instructions (or groups
of instructions) - Iteration (repetition) of instructions (or groups
of instructions)
90Sequence in Structured English
- Each instruction executed in turn, one after
another - E.g.
- get client contact name
- sale cost item cost ( 1 - discount rate )
- calculate total bonus
- description new description
91Selection in Structured English
- One or other alternative course is followed,
depending on result of a test - if client contact is Acme
- set discount rate to 5
- else
- set discount rate to 2
- end if
92Iteration in Structured English
- Instruction or block of instructions is repeated
- Can be a set number of repeats
- Or until some test is satisfied, for example
- do while there are more staff in the list
- calculate staff bonus
- store bonus amount
- end do
Pseudo-code broadly similar.
93Activity Diagrams
- Are part of UML notation set
- Can be used for operation logic specification,
among many other uses - Are easy to learn and understand
- Have the immediacy of graphical notation
- Bear some resemblance to old-fashioned flowchart
technique
94Simple Activity Diagram
Link to CreativeStaff
Create new StaffGrade
Link to previous StaffGrade
Set previous StaffGrade gradeFinishDate
95Activity Diagram with Selection
not approved by Director
Check approval for grade change
Print approval request
approved by Director
Link to CreativeStaff
Create new StaffGrade
Link to previous StaffGrade
Set previous StaffGrade gradeFinishDate
96Activity Diagram with Selection and Iteration
97Package it all up
- Pack up design into discrete physical units that
can be edited, compiled, linked, and reused. - Construct physical modules
- Ideally use one package for each subsystem
- System decomposition might not be good for
implementation. - Two design principles for packaging
- Minimize coupling
- Classes in client-supplier relationships are
usually loosely coupled - Large number of parameters in some methods mean
strong coupling (gt 4-5) - Avoid global data
- Maximize cohesiveness
- Classes closely connected by associations gt same
package
98Packaging Heuristics
- Each subsystem service is made available by one
or more interface objects within the package - Start with one interface object for each
subsystem service - Try to limit the number of interface operations
(7?2) - If the subsystem service has too many operations,
reconsider the number of interface objects - If you have too many interface objects,
reconsider the number of subsystems
99Questions?
100Reading Bruegge and Dutoit Chapters 8 and 9
Object Design Pressman Chapter 22 -
Object-Oriented Design