Information Hiding: Coupling and Cohesion lecture 2 ECE 521

Generalization
Example
Payment
Attribute
sale
amount
Relationship
Cach
Payment
Credit
Payment
Check
Payment
Each sub class inherit the attribute and Relationship
in super class
Representing Generalization
• Generalization
• Abstraction of common features among multiple
classes, as well as their relationships, into a more
general class
• Subclass
• A class that has been generalized
• Superclass
• A class that is composed of several generalized
subclasses
A.3
Is – a Rule
• All the members of sub type set must be member of
their super type set
• In natural language this can usually be infomally
tested by forming the statement
• Subtype is a Super type
Representing Generalization
• Discriminator
• Shows which property of an object class is being
abstracted by a generalization relationship
• Inheritance
• A property that a subclass inherits the features from its
superclass
• Abstract Class
• A class that has no direct instances, but whose
descendents may have direct instances
• Concrete Class
• A class that can have direct instances
A.5
A.6
A.7
Representing Aggregation
• Aggregation
• A part-of relationship between a component object and an
aggregate object
• Example: Personal computer
• Composed of CPU, Monitor, Keyboard, etc
A.8
Coupling and Cohesion
Characteristics of Good Design
• Component independence
• High cohesion
• Low coupling
• Exception identification and handling
• Fault prevention and fault tolerance
Coupling
• The interdependence or interrelationships of the
modules
• Interaction coupling
• Relationships with methods and objects
• through message passing
Slide 11
Coupling criteria
Size
- refers to the number of connections between modules,
it is less work to connect other modules to a module with
a smaller interface
Coupling: Degree of dependence
among components
No dependencies
Highly coupled-many dependencies
Loosely coupled-some dependencies
High coupling makes modifying
parts of the system difficult, e.g.,
modifying a component affects all
the components to which the
component is connected.
Levels of coupling
High Coupling
Content Coupling
2.Common Coupling
3.Control Coupling
4.Stamp Coupling
5.Data Coupling
Uncoupled
Low Coupling
Types of Interaction Coupling
Level
Good
Bad
Slide 15
Type
Description
No Direct Coupling
Methods don't call each other
Data
Calling method passes object, called method uses the entire object
Stamp
Calling method passes object, called method uses only part of the object
Control
Calling method passes a control variable whose value controls the execution of
the called method
Common or Global
Methods refer to a "global data area" that is outside of the individual objects
Content or
Pathological
A method of one object refers to the hidden part of another object.
Content coupling
• Definition: One component references contents of
another
• Example:
• Component directly modifies another’s data
• Component refers to local data of another component in
terms of numerical displacement
• Component modifies another’s code, e.g., jumps into the
middle of a routine
Example of Content Coupling-1
Part of program handles lookup for customer.
When customer not found, component adds customer by directly
modifying the contents of the data structure containing
customer data.
Example of Content Coupling-2
Part of program handles lookup for customer.
When customer not found, component adds customer by directly
modifying the contents of the data structure containing
customer data.
Improvement:
When customer not found, component calls the AddCustomer()
method that is responsible for maintaining customer data.
Common Coupling
• Definition: Two components share data
• Global data structures
• Common blocks
• Usually a poor design choice because
• Lack of clear responsibility for the data
• Reduces readability
• Difficult to determine all the components that affect a data element
(reduces maintainability)
• Difficult to reuse components
• Reduces ability to control data accesses
Example-1
Process control component maintains current data
about state of operation. Gets data from multiple
sources. Supplies data to multiple sinks.
Each source process writes directly to global data store. Each sink process
reads directly from global data store.
Example-2
Process control component maintains current data
about state of operation. Gets data from multiple
sources. Supplies data to multiple sinks.
Each source process writes directly to global data store. Each sink
process reads directly from global data store.
Improvement
Data manager component is responsible for data in data store.
Processes send data to and request data from data manager.
Control Coupling
• Definition: Component passes control parameters to
coupled components.
• May be either good or bad, depending on situation.
• Bad when component must be aware of internal structure
and logic of another module
• Good if parameters allow factoring and reuse of functionality
Example
• Acceptable: Module p calls module q and q passes back flag
that says it cannot complete the task, then q is passing data
• Not Acceptable: Module p calls module q and q passes back
flag that says it cannot complete the task and, as a result,
writes a specific message.
Stamp Coupling
• One component passes more data then needed to
another
void swap(int v[], int i, int j);
double calcsalary(Employee& e);
● Often involves records (structs) with lots of fields
● Entire record is passed, but only a few fields are used
Example-1
Customer billing system
The print routine of the customer billing accepts a customer
data structure as an argument, parses it, and prints the name,
address, and billing information.
Example-2
Customer Billing System
The print routine of the customer billing accepts a customer
data structure as an argument, parses it, and prints the name,
address, and billing information.
Improvement
The print routine takes the customer name, address, and billing
information as an argument.
Data Coupling
• Definition: Two components are data coupled if there
are homogeneous data items.
• Every argument is simple argument or data structure in
which all elements are used
• Good, if it can be achieved.
• Easy to write contracts for this and modify component
independently.
Key Idea in Object-Oriented
Programming
• Object-oriented designs tend to have low coupling.
Cohesion
• Definition: The degree to which all elements of a component are
directed towards a single task and all elements directed towards
that task are contained in a single component.
• Internal glue with which component is constructed
• All elements of component are directed toward and essential for
performing the same task
• High is good
Cohesion
• “Single-mindedness of a module”
• Method cohesion
• A method should do just a single task
• Class cohesion
• A class should represent just one thing
• Generalization/specialization cohesion
• Addresses inheritance
• Should represent "a-kind-of" or "is-a"
Slide 30
Levels of cohesion
High Cohesion
7.Functional
7.Informational
5.Communicational
4.Procedural
3.Temporal
2.Logical
1.Coincidental
Low Cohesion
Types of Method Cohesion
Level
Type
Description
Good
Functional
A method performs a single task
Sequential
Method performs two tasks, the output of the first is the input of the second
Communicational
Method combines two functions that use the same attributes (calc current and final
GPA)
Procedural
Method supports many loosely related functions (calc current GPA, print, calc final
GPA, print)
Temporal or Classical
Method supports multiple functions related in time (initialize all variable, print all
reports)
Logical
Method supports many functions controlled by a passed control variable
Coincidental
Method's purpose cannot be determined, or it supports multiple unrelated functions
Bad
Slide 32
Types of Class Cohesion
Level
Type
Description
Good
Ideal
Class has none of the mixed cohesions
Mixed-Role
Class has some attributes that relate to other classes on the same layer, but the attributes are
unrelated to the semantics of the class
Mixed-Domain
Class has some attributes that relate to classes on a different layer.
Mixed-Instance
Class represents two different types of objects. Should be decomposed into two classes.
Worse
Slide 33
Coincidental Cohesion
• Definition: Parts of the component are only related by
their location in source code
• Elements needed to achieve some functionality are
scattered throughout the system.
• Accidental
• Worst form
Example
•
•
•
•
Print next line
Reverse string of characters in second argument
Add 7 to 5th argument
Convert 4th argument to float
Logical Cohesion
• Definition: Elements of component are related
logically and not functionally.
• Several logically related elements are in the same
component and one of the elements is selected by
the client component.
Example-1
• A component reads inputs from tape, disk, and network.
All the code for these functions are in the same
component.
• Operations are related, but the functions are significantly
different.
Example-2
• A component reads inputs from tape, disk, and network.
All the code for these functions are in the same
component. Operations are related, but the functions are
significantly different.
Improvement
• A device component has a read operation that is
overridden by sub-class components. The tape sub-class
reads from tape. The disk sub-class reads from disk. The
network sub-class reads from the network.
Temporal Cohesion
• Definition: Elements of a component are related by
timing.
• Difficult to change because you may have to look at
numerous components when a change in a data
structure is made.
• Increases chances of regression fault
• Component unlikely to be reusable.
Example-1
• A system initialization routine: this routine contains all of the
code for initializing all of the parts of the system. Lots of
different activities occur, all at init time.
Example-2
• A system initialization routine: this routine contains all of the
code for initializing all of the parts of the system. Lots of
different activities occur, all at init time.
Improvement
• A system initialization routine sends an initialization message to
each component.
• Each component initializes itself at component instantiation
time.
Procedural Cohesion
• Definition: Elements of a component are related only
to ensure a particular order of execution.
• Actions are still weakly connected and unlikely to be
reusable
Example
...
Read part number from data
base
update repair record on
maintenance file.
...
• May be useful to abstract the
intent of this sequence.
Make the data base and
repair record components
handle reading and
updating. Make component
that handles more abstract
operation.
Communicational Cohesion
• Definition: Module performs a series of actions
related by a sequence of steps to be followed by the
product and all actions are performed on the same
data
Example
• Update record in data base
and send it to the printer.
• database.Update (record).
• record.Print().
Sequential Cohesion
• The output of one component is the input to another.
• Occurs naturally in functional programming languages
• Good situation
Informational Cohesion
• Definition: Module performs a number of actions, each with
its own entry point, with independent code for each action,
all performed on the same data.
• Different from logical cohesion
• Each piece of code has single entry and single exit
• In logical cohesion, actions of module intertwined
• ADT and object-oriented paradigm promote
Functional Cohesion
• Definition: Every essential element to a single
computation is contained in the component.
• Every element in the component is essential to the
computation.
• Ideal situation.
Cohesion in coding
refers to the degree to which component’s
instructions are functionally related
Levels of cohesion
Coincidental cohesion
occurs when the operations in a routine have no
discernable relationship to each other
Levels of cohesion - coincidental
FUNCTION A
FUNCTION B
FUNCTION C
FUNCTION D
FUNCTION F
functions have little or no
relationship to one another
Levels of cohesion - coincidental
multiple completely unrelated actions
short printNextLine(String inStr, short x, short y) {
System.out.println(inStr);
resetScreen();
return x+y;
}
Can you tell what printNextLine intend to do?
Levels of cohesion
Logical cohesion
occurs when several logically related operations are
stuffed into the same module and only one of the
operations is selected
Levels of cohesion - logical
FUNCTION A
FUNCTION B
logic
FUNCTION C
functions appear to be
related because they fall
into the same logical class
of function (they perform a
set of related actions)
Levels of cohesion - logical
a series of related actions, one is selected by the caller
short eval(short opCode, short x[], short y[]) {
short m1,m2;
switch (opCode){
case 1 : m1=max(x); return m1;
case 2 : m1=max(x); m2=max(y); return (m1>m2?m1:m2);
case 3 : m1=min(x); return m1;
case 4 : m1=min(x); m2=min(y); return (m1<m2?m1:m2);
default: return 0;
}
}
Levels of cohesion
Temporal cohesion
occurs when operations are combined into a module
because they are all done at the same time
Levels of cohesion - temporal
TIME TO
TIME TO + X
TIME TO + 2X
functions are grouped
together because of “time”
(actions related in time)
Levels of cohesion - temporal
a series of actions related in time
void init() {
openAccountDB();
openTransactionDB();
resetTransactionCount();
System.out.println(“Balance update in progress…“);
return;
}
Levels of cohesion
Procedural cohesion
occurs when operations in a module are done in a
specified order, the operations in procedural cohesion do
not share the same data
Levels of cohesion - procedural
FUNCTION A
FUNCTION B
FUNCTION C
functions accomplish
different tasks, yet have
been combined because the
actions correspond to the
sequence of steps in some
operation
Levels of cohesion - procedural
a series of actions related by sequence of steps to be
followed by the result (a series of actions sharing sequence
of steps)
void sumOfTran() {
DB[0]=0;
CR[0]=0;
for (short i=1; i<= noAcct; i++){
DB[0] += DB[i];
CR[0] += CR[i];
}
return;
}
Levels of cohesion
Communicational cohesion
occurs when a sequence of steps, related to some
operation, operate on the same data
Levels of cohesion - communicational
FUNCTION A
FUNCTION B
FUNCTION C
functions perform
operations on the same
body of data (data is passed
between functions)
Levels of cohesion - communicational
a series of actions related by sequence of steps to be
followed by the product and if all the actions are performed
on the same data (a procedural cohesion but on the same
data)
short stackPop2() {
short next = stack[top--];
short nextNext = stack[top--];
return (next+nextNext);
}
Levels of cohesion
Informational cohesion
occurs when a module contains independent actions that
must be performed on the same data structure (gives the
ability to "package" all of the functionality that relates
to a given data structure)
Levels of cohesion - informational
FUNCTION A
FUNCTION B
FUNCTION C
functions are related by the
fact that they perform
actions on a single data
structure
Levels of cohesion - informational
a number of actions, each with its own entry point and
independent code, all performed on the same data
short op(char opCode, short x, short y) {
switch (opCode){
case ’+’ : return (x+y);
case ’-’ : return (x-y);
case ’*’ : return (x*y);
case ’/’ : return (x/y);
default: return 0;}
}
Levels of cohesion
Functional cohesion
strongest and best kind of cohesion – when a module
performs one and only one operation
Levels of cohesion - functional
FUNCTION A, part 1
FUNCTION B, part 2
FUNCTION C, part 3
functions work collectively
to accomplish a single welldefine action
Levels of cohesion - functional
performs exactly one action or achieves a single goal
short sumOfArray(short number[]) {
short result = 0;
for (short i=0; i< number.len; i++)
result += number[i];
return result;
}
Dynamic Modeling:
State Diagrams
Dynamic Modeling:
State Diagrams
A.72
•
State
•
A condition during the life of an object during
which it satisfies some conditions, performs some
actions or waits for some events
•
Shown as a rectangle with rounded corners
•
State Transition
•
The changes in the attribute of an object or in the
links an object has with other objects
•
Shown as a solid arrow
•
Diagrammed with a guard condition and action
•
Event
•
Something that takes place at a certain point in
time
A.73