Chapter 7 - OOA and OOD
Chapter 7 - OOA and OOD
Software Engineering - I
An Introduction to Software Construction Techniques for Industrial
Strength Software
A complex system that works is invariably found to have evolved from a simple system that
worked. The structure of a system also plays a very important role. It is likely that we
understand only those systems which have hierarchical structure and where intra-component
linkages are generally stronger than inter component linkages. That leads to loose coupling, high
cohesion and ultimately more maintainability which are the basic design considerations. Instead
of being a collection of loosely bound data structures and functions, an object-oriented software
system consists of objects which are, generally, hierarchical, highly cohesive, and loosely coupled.
Some of the key advantages which make the object-oriented technology significantly attractive
than other technologies include:
• Clarity and understandability of the system, as object-oriented approach is closer to the
working of human cognition.
• Reusability of code resulting from low inter-dependence among objects, and provision of
generalization and specialization through inheritance.
• Reduced effort in maintenance and enhancement, resulting from inheritance,
encapsulation, low coupling, and high cohesion.
Before talking about how to derive and object-oriented design, we first need to understand the
basic difference between object-oriented and function oriented (or action oriented) approach.
Functions
Data
In this diagram, the ovals depict the function while rectangles/squares depict data. Since a
function contains dynamic information while data contains only static information, if the function
and data are managed separately, the required data components can be found by scanning a
function but the functions that use a particular data cannot be found by just looking at the data.
That is, the function knows about the data it needs to use but the data do not know about the
functions using it. That means, it is easy to make a change in a function since we would know
which data components would be affected by this change. On the other hand, changing a data
structure would be difficult because it would not be easy to find all the functions that are using
this data and hence also need to be modified.
In the case of OO design since data and function are put together in one class, hence, in case of a
change, the effected components can be identified easily and the effect of change is localized.
Therefore, maintenance becomes relatively easy as compared to function-oriented approach.
The state of an object encompasses all of the properties of the object and their current values. A
property is an inherent or distinctive characteristic. Properties are usually static. All properties
have some value. The state of an object is encapsulated within the object.
Behavior is how an object acts and reacts in terms of its state changes and message passing. The
behavior of an object is completely defined by its actions. A message is some action that one
object performs upon another in order to elicit a reaction. The operations that clients may
perform upon an object are called methods.
The structure and behavior of similar objects are defined in their common class. A class
represents an abstraction - the essence or the template of an object. A class specifies an interface (
the outside view - the public part) and defines an implementation ( the inside view - the private
part). The interface primarily consists of the declaration of all the operations applicable to
instances of this class. The implementation of a class primarily consists of the implementation of
all the operations defined in the interface of the class
2.2. Classification
The most important and critical stage in the OOA and OOD is the appropriate classification of
objects into groups and classes. Proper classification requires looking at the problem from
different angles and with an open mind. When looked at from different perspectives and
analyzed with different set of characteristics, same object can be classified into different
categories. Let us try to understand this with the help of an example.
Responsibility-Driven
Data-Driven carry things, communicate,
head, tail, body, leg maintain its living system
Behavior-Driven
walk, run, eat
Here, we can take a data-driven, behaviour driven, or responsibility driven perspective and will
categorize the horse accordingly.
Abstraction is an extremely powerful technique for dealing with complexity. Unable to master
the entirety of a complex object, we ignore its essential details, dealing instead with generalized,
idealized model of the object. An abstraction focuses on the outside view of an object, and hence
serves to separate an objects external behavior from its implementation. Deciding upon the right
set of abstractions for a given domain is the central problem in object oriented design.
Abstraction and encapsulation are complementary concepts. Abstraction provides the outside
view to the client and encapsulation prevents clients from seeing its inside view. For abstraction
to work, implementation must be encapsulated. Encapsulation hides the details of the
implementation of an object. Intelligent encapsulation localizes design decisions that are likely to
change. The ability to change the representation of an object without disturbing any of its clients
is the essential benefit of encapsulation.
In an association relationship, when object A “uses” object B, then A may send messages to B.
The relationship defines visibility among objects.
The aggregation relationship defines part-of structure among objects. When object A is part of the
state of object B, A is said to be contained by B. There are some tradeoffs between aggregation
and association relationships. Aggregation reduces the number of objects that must be visible at
the level of enclosing objects and may lead to undesirable tighter coupling among objects.
of one another. The only limitation is that an object must be alive or has to be instantiated before
a message can be sent to it.
1) The subsystem layer. Contains a representation of each of the subsystems that enable the
software to achieve its customers defined requirements and to implement the technical
infrastructure that supports customer requirements.
2) The class and object layer. Contains the class hierarchies that enable the system to be created
using generalization and increasingly more targeted specializations. The layer also contains
design representations for each object.
3) The message layer. Contains the details that enable each object to communicate with its
collaborators. This layer establishes the external and internal interfaces for the system.
4) The responsibility layer. Contains the data structures and algorithmic design for all
attributes and operations for each object.
Classes Objects
methods algorithms
relationships messaging
behavior control
Translating the analysis model into a design model during object design
Once all the model components have been identified, we will eliminate the redundant or
irrelevant components by again analyzing the text and the context of the problem.
Let’s now try to understand this with the help of an example:
Problem Statement:
A simple cash register has a display, an electronic wire with a plug, and a numeric keypad, which
has keys for subtotal, tax, and total. This cash storage device has a total key, which triggers the
release on the drawer. The numeric buttons simply place a number on the display screen, the
subtotal displays the current total, the tax key computes the tax, and the total key adds the
subtotal to the tax.
Nouns (initial)
We now analyze the identified nouns and try to establish whether they would be stand-alone
classes in our domain or not. Outcome of this analysis is shown below.
Register
Display
Wire Æ Irrelevant
Plug Æ Irrelevant
Keypad
Keys
Devices Æ Vague
Release Æ Irrelevant
Drawer
Buttons Æ Redundant
Screen Æ Redundant
Number Æ Attribute
Total Æ Attribute
Tax Æ Attribute
0-9 Key
Value Æ Attribute
Money
Subtotal Key
Tax Key
Total Key
We will continue with technique to identify all the constituent components of the model and
derive our object-oriented design.
6. The Notation
Many different notations are used for documenting the object oriented design. Most popular of
these include, Rumbaugh, Booch, and Coad, and UML(Unified Modeling Language). We will be
using UML to document our design. Although the notation is very comprehensive and detailed,
but the key features of this notation are presented in the following diagram.
While selecting objects, the following considerations should be kept in mind for a simpler (and
better) object model.
1. Every object that you put in your object model should have some responsibility or role to
play in the problem domain. You need to know each object, its attributes, and services. If
there is no way to know about the object, remove it from the object model.
2. Avoid having controller objects because controllers usually end up with functionality that’s
better done by other objects themselves, making the message passing more complicated, and
resulting in higher coupling. Use delegation instead. Note the difference between controlling
and delegation; a controller wants to do every thing by himself (doesn’t trust anyone), while
a good manager delegates responsibility (and takes credit).
3. In large systems several objects are likely to have similar or even identical responsibilities.
Look for such objects and seek a common name to simplify the object model.
4. Use meaningful class names, names that describe objects in that class. Try to use names from
the domain vocabulary to avoid confusion.
For each object include the attributes that come to mind when you first think about the object.
The criteria for the inclusion of an attribute is that it should be included if the system needs to
know its value and it cannot get it any other way. Don not add an attribute for an association or
aggregation. Examples of attributes are: number, name, address, date, time, operational state,
phone, status, threshold, type, etc. In particular, consider the following attributes for different
types of objects.
Like object selection, there are a number of issues that every designer must be aware of while
defining attributes of an object. These are:
1. An attribute that varies over time, e.g., price of an item, should be replaced by an additional
class with an effective date and value.
2. An attribute that may have a number of values should be replaced by a new class and an
object connection.
3. Replace “yes/no” type attributes with “status” type attributes for flexibility.
4. If there are classes with common attributes and generalization-specialization makes good
sense, then add a generalization class and factor out the commonality.
Software objects do things that the system is responsible to do with regard to that object. By
putting the services with the attributes they work on results in lower coupling and stronger
cohesion, and increased likelihood of reuse. The basic principle is to keep data and action
together for lower coupling and better cohesion. The basic services, done by all (such as get, set,
create, initialize), are not shown in the object model. While establishing the services for an object,
the following fundamental questions should be asked:
While establishing services of certain specific types of objects, the following should be
considered:
1. For an actor, consider: calculate for me, rate me, is <value>, rank participants, calculate over
participants.
2. For a participant, consider: calculate for me, rate me, is <value>, rank transactions, calculate
over transactions.
3. For a place, consider: calculate for me, rate me, is <value>, rank transactions, calculate over
contents, calculate over container line items.
4. For a Transaction, consider: calculate for me, rate me, is <value>, how many, how much,
rank transaction line items, rank subsequent transactions, calculate over transaction line
items, calculate over subsequent transactions.
5. For a line item, consider: calculate for me, rate me.
6. For an item, consider: calculate for me, rate me, is <value>, how many, how much, rank,
calculate over specific items.
• balance the cash in the drawer with the amount recorded by the point-of-sale system.
8.1.1.2. Why ?
• speed up checkout time
• reduce the number of pricing errors
• reduce the labour required to ticket the item with a price, originally and when prices
change.
8.1.1.3. Summary
to help each cashier work more effectively during checkout, to keep good records of each sale, and to
store more efficient store operations.
• cashier
• head cashier
• customer
Shelf
The system does not keep track of the shelves.
Session
Is it important? It is important in order to evaluate a cashier’s performance.
A store is a kind of sales outlet. Perhaps over time, Connie will expand to other kinds of
sales outlets. Stores might be specialized into kinds of stores. For now on leave store as it
is.
Kinds of sales:
- sales, returns
- only different is that the amount is positive or negative. Is there any other difference?
Prices:
- regular price, and promotional (sales) price
Payment:
- cash, check, and charge are kind of payments
Payment Price
Object Hierarchy
Stote Sale
Cash Drawer
Whole-Part Structures
Payment Sales
Association Relationships
8.4.2. Define Attributes, Services, and Links - What I know, What I do, and Who
I know?
Actors:
person
Attributes: name, address, phone
Services:
Participants:
cashier
Attributes: number, password, authorization level, current session
Services: isAuthorized, assess Performance
Places:
store
Attributes: name
Services: get item for UPC, get cashier for number
Tangible things:
item
Attributes: number, description, UPCs, prices, taxable
attributes with repeating names - create new objects
UPC, Price (specialization - promotional price)
Services: get price for a date, how much for quantity
Who I Know? UPC, Price, tax category, sale line item
register
Attributes: number
Services: how much over interval, how many over interval
Who I know? store, session, cash drawer (part of register)
cash drawer
Attributes: balance, position (open, close), operational state
Services: open
Who I know? register
Tax Category
Attributes: category, rate, effective date
Services: just the basic services - get, add, set - don’t show
Who I know? items?
Transactions:
sale
Attributes: date and time
Services: calculate subtotal, calculate total, calculate discount, calculate
tax, commit
Who I Know? session, payment, SLIs
return
Attributes: return price, reason code, sale date, sale price
Services:
Who I Know?
Services:
who I know: sale
Cheque Charge
session
Attributes: start date, end date, start time, end time
Services: how much money collected over interval, how many sales
Who I know? register, cashier, store, sales
Promotional Price
Person Sale
Authorized
Return Line Item Cash Payment
Payment
Cheque Charge
A series of diagrams can be used to describe the dynamic behavior of an object-oriented system.
This is done in terms of a set of messages exchanged among a set of objects within a context to
accomplish a purpose. This is often used to model the way a use case is realized through a
sequence of messages between objects.
UML provides two different mechanisms to document the dynamic behaviour of the system.
These are sequence diagrams which provide a time-based view and Collaboration Diagrams which
provide an organization-based view of the system’s dynamics.
Lifeline Message
The boxes denote objects (or classes), the solid lines depict messages being sent from one object to
the other in the direction of the arrow, and the dotted lines are called life-lines of objects. The life
line represents the object’s life during interaction. We will discuss this in more detail later.
These concepts are further elaborated with the help of the following sequence diagram.
X-Axis (objects)
member: :Book
book:Book
LibraryMember Copy
borrow(book) Object
ok = mayBorrow()
Life
Y-Axis (time)
Line
message
[ok] borrow(member)
Activation
setTaken(member) box
condition
As shown above, in a sequence diagram, objects (and classes) are arranged on the X-Axis
(horizontally) while time is shown on the Y-Axis (vertically). The boxes on the life-line are called
activation boxes and show for how long a particular message will be active, from its start to
finish. We can also show if a particular condition needs to occur before a message is invoked
simply by putting the condition in a box before the message. For example, object
member:LibraryMember sends a message to object book:book if the value of ok is true.
An interaction between two objects is performed as a message sent from one object to another. It
is most often implemented by a simple operation call. It can however be an actual message sent
through some communication mechanism, either over the network or internally on a computer.
If object obj1 sends a message to another object obj2 an association must exist between those two
objects. There has to be some kind of structural dependency. It can either be that obj2 is in the
global scope of obj1, or obj2 is in the local scope of obj1 (method argument), or obj1 and obj2 are the
same object.
A message is represented by an arrow between the life lines of two objects. Self calls are also
allowed. These are the messages that an object sends to itself. This notation allows self calls. In
the above example, object member:LibraryMember sends itself the mayBorrow message. A message
is labeled at minimum with the message name.
Arguments and control information (conditions, iteration) may also be included. It is preferred to
use a brief textual description whenever an actor is the source or the target of a message.
The time required by the receiver object to process the message is denoted by an activation-box.
Synchronous
Asynchronous
<<create>>
Create
<<destroy>>
Destroy
9.1.2.1. Synchronous Messages
Synchronous messages are “call events” and are denoted by the full arrow. They represent nested
flow of control which is typically implemented as an operation call. In case of a synchronous
message, the caller waits for the called routine to complete its operation before moving forward.
That is, the routine that handles the message is completed before the caller resumes execution.
Return values can also be optionally indicated using a dashed arrow with a label indicating the
return value. This concept is illustrated with the help of the following diagram.
:A :B
doYouUnderstand()
return
Caller
yes (optional)
Blocked
• Don’t model a return value when it is obvious what is being returned, e.g. getTotal()
• Model a return value only when you need to refer to it elsewhere, e.g. as a parameter
passed in another message.
• Prefer modeling return values as part of a method invocation, e.g.
ok = isValid()
2 : process
3 : add course
4 : <<create>> aCourse :
Course
:A :B
<<destroy>>
Collaboration diagrams have basically two types of components: objects and messages. Objects
exchange messages among each-other. Collaboration diagrams can also show synchronous,
asynchronous, create, and destroy message using the same notation as used in sequence
diagrams. Messages are numbered and can have loops
: ProfessorCourseManager
Sequence diagrams are best to see the flow of time. On the other hand, static object connections
are best represented by collaboration diagrams. Sequence of messages is more difficult to
understand in collaboration diagrams than in the case of sequence diagrams. On the other hand,
object organization with control flow is best seen through collaboration diagrams. It may be
noted that complex control is difficult to express anyway but collaboration diagrams can become
very complex very quickly.
Judging the quality of a design is difficult. We can however look at certain object-oriented design
attributes to estimate its quality. The idea is to analyze the basic principle of encapsulation and
delegation to judge whether the control is centralized or distributed, hence judging the coupling
and cohesion in a design. This will tell us how maintainable a design is.
You may also recall our earlier discussion of coupling and cohesion. It can be easy to see that OO
design yield more cohesive and loosely coupled systems.
The issue of centralized versus distributed control can be illustrated with the help of the
following example.
Desired des
Temp ire dTe
p()m
Actual actualTemp() Heat Flow
Furnace
Temp Regulator
ese n t ()
Occupancy n yonePr
a
In this case, the room is not encapsulated as one entity and three different objects namely Desired
Temp, Actual Temp, and Occupancy maintain necessary information about a room. In this case the
Heat Flow Regulator has to communicate with three different objects.
If we encapsulate the three objects into one Room object as shown below, then the Heat Flow
Regulator will need to communicate with one object, hence the overall coupling of the system
will be reduced.
Room
Desired
Temp desiredTemp()
Occupancy
This happened because in the first case intelligence is distributed while in the second case it is
encapsulated. However, the control is still centralized as the Heat Flow Regulator has the control
logic that first analyses the values from different queries and then makes a decision about turning
the furnace on of off. We can improve the situation even further by delegating this responsibility
to the Room object as shown below.
Room
Desired
Temp
Occupancy
By doing that we reduce coupling even further because now we have made Room more cohesive
by putting the function with the related data and have thus reduced the number and types of
messages being sent from the regulator to the room.
That is, we can reduce the coupling of a system by minimizing the number of messages in the
protocol of a class. The problem with large public interfaces is that you can never find what you
are looking for…smaller public interfaces make a class easier to understand and modify. This can
be further elaborated with the help of the following example. Suppose we have two functions
defined for setting the desired temperature in the room:
• SetMinimumValue(int aValue)
• SetMaximimumValue(int aValue)
We can reduce the total number of messages in the protocol of this class by consolidation these as
shown below, hence reducing the overall complexity of the protocol.
It is however important to use these kinds of heuristics judiciously and care must be taken so that
the scope of the function does not go beyond providing one single operation.