You are on page 1of 6

18 - G W P : PATTERNS

FOR ASSIGNING RESPONSIBILITIES

18.11 Low Coupling

Solution Assign a responsibility so that coupling remains low.

Problem How to -support low dependency and increased


-- reuse?
Coupling is a measure of how stpngly one class is connected to, has knowie*
By Atang Setiawan at 1:05 pm, May 05, 2008 of, or relies upon other classes. A class With low-(or--weak) couiliiig i s o _ t - d q e -
dent on too many other classes; "too many" is context T i e n d e n t b-mi 5-
examined. - -- - -
I-
-
A class with
d
high (or
---
strong) coupliEg r e l p s n many other classes. S x L
claCsFare-unGsira6le;
--- they suffer from the fdlowing problems:
Changes in related classes force local changes.
Harder to understand in isolation.
Harder to reuse because -- its use requires
-
the additional presence of the
classes it is dependent upon.

Example Consider the following partial class diagram from a point-of-sale terminal appli-
cation:

m Payment

Assume we have a need to create a Payment instance and associate it with the
Sale. What class should be responsiRG for-<hi&? Since a POST "records" a Pa?-
ment in the real-world domain, the Creator pattern suggests POST as a candi-
date for creating the Payment. The Post instance could then send an
addpayment message to the Sale, passing along the new Payment as a parame-
ter. A possible partial collaboration diagram reflecting this is shown in Figure
18.9.

---&

p : Pavrnent

Figure 18.9 POST creates Payment.


.-- -

This assignment of responsibilities couples the POST class to knowledge of the


Payment class. An alternative solution to creating the Payment and associating
UP-

18 - GRASP: PAATTERNSFOR ASSIGNlNG ~EsPONSIBILITIES

it with the Sale is shown in Figure 18.10.

F i g u r e 18.10 Sale creates Payment.

Which design, based on assignment of rgsponsibilities, supports Low Coupling?


In both cases we Gill SSSumeethe Sale -- &=st -- eventually he coupled to knowledge
of a ~ ~ m e Design
n ; o n e , in which the Pmt- creates the P a y m a t , adds coupling
O ~ ~ C to_Pwent,
ST while Design 'I'wo, in which-the Sale
- does--the creation of a
Payment,'does
- -- r&:iGeaSe the coupling. Purely s m the point ofview of cou-
piing, Design Two is preferable because overall l o - ~_coupling
r is maintained.
This an exampie where t-atterns-low Coupling and Creator-may suggest
different solutions. In practice, the level of coupling alone can not be considered
in isolation from other principles such as Expert and High Cohesion. Neverthe-
less, it is one factor to consider in improving a design.

-Discussion Low Coupling is a principle to-keep in mind during all designctecisions; it is a n


- underlying goal to continually consider. It is an evaluative pattern which a
designer applies while evaluating all design decisions.
In object-oriented languages such as C++, Sava, and Smalltalk, common forms
of mupling-&om a p e x to FypeY-include: -
3 - . to a
QpeX has an attribute (data member or instance variable) that refers
q p e Y insta-or QPeY itself
a Q p e X has a method-which
- references a n.- instance of TypeY, or TypeY itself,
by any means. Tnese typically include a parameter or local variable of type
FypeY, or the object returned from a message being an instance of ;rSpeY
m QpeX is a direct or indirect subclass
- --
of FypeY.
?$iDeYis a n interface, and F y p X implements that interface.
. .- --

Low Coupling encourages assigning a responsibility so that its placement does


not increase the coupling to such a level that it leads to the negative results that
high coupling can produce.
Low Coupling supports the design of classesthat are more independenk, which
reduces the impact of changes, and more reusable, which improves the opportu-
nity for higher productivity. It can not be cansidered in isolation from other pat-
terns such as l3xpei.t and High Cohesion, but rather needs to be included as m e
of severai design principles that influence a choice in assigning a responsibility.
Coupling may not be that important if reuse is not a goal. As a support to
improve reuse of components by making them more independent, the entire con-
text of reuse goals must be taken into consideration before an effort is made to
minimize coupling. For example, excessive time is sometimes spent on trying to
achieve reusable components for future "mythical" projects, even though there is
no clear indication there is a need for reuse of the component. This is not to say
trying to achieve reuse is wasted effort, but the effort should be tempered by
cost-benefit conside~atiofls.
, - :

A subclass is strongly coupled to its superclass. The decision to derive from a


superclass needs to be carefully considered since it is such a strong form of c m -
pling. For example? suppose that objects need to be stored persistently in a rela-
tional or object database. In this case, it is a relatively cornmen, but somewhat
undesirable, design to create aun abekraet superclass called PersistentObject- from
which other classes derive. The disa&sip~tageof this subclassing is that ik highly
couples doma& objects to a particular service, whereas the advantage is auto-
matic inheritance of persistence behavior, a "marriage of conveniencen-seldom
a wise choice in relationships!
There is no a'mlate measure of w h e s c q l i n g g i s too &&.What is important is
that a d e ~ d o p e can
r gauge t h e c a r r e ~degree
t of coupling, and assess if increas-
ing it will bad to problems. In general, classes which are inherently very generic
in nature, m d v i t h a high probability for EUE, should have especially low cou-
pling.
The extreme case of IAYN Coupling is %he= there is very IitQe or no coupling
between classes. This is not desirable because a central metaphor of object t e c h
nology is a systen~of connected objects t h a t communicate vie messages. If Low
Coqding is i&ez to excess, it yields a poor design beca~lseit leads to a few inco-
hesive, bfoated, and complex active objects that do all the work, with many very
passive zero-coupled objects that act as simple data repositories. &me moderate
degree of coupling between classes is normal and necessary in order to create an
object-oriented system in which tasks are fulfilled by a collaboration between
connected objects.

Benefits FA not effected by chznges in other components


oil simple to understand in isolation
a convenient to reuse
18 - GRASP: PATTERNS RESPONSIBILITIES
FOR ASSIGNING

18.12 High Cohesion

Solution Assign a responsibility s o t h a t cohesion r e m a i n s high.


<
- -
Problem HOW to keep complexity manageable?:
- - -
In terms of object-oriented design, cohesion (or- -more -- ~e~cifically functional
,
cohesion_)is a measure of how strangly related a n d focused the responsibilities Gf
a class a=. Kclass w i t h - f i i g h m a t e d does not do--a
tFemendous
. -. amount of work, hi; high ~ I t e s i-o n .
A class with low cohes&n does manxunrelated things or does - too much
---work.
Such classes are undesirable; they suffer from the following problems:
E m hard to comprehend
Ii hard to reuse -
1: m hard to maintain
m delicate; constantly effected by change
Low cohesion classes often represent a very "large-grain" of abstraction, or have
taken on responsibilitiesthat should have been delegated to other objects,

Example The same example problem used in the Low Coupling pattern can be analyzed
for High Cohesion.
-- -
kssu<6-we h a v e - e e e d to create aa_(c.ash)
Parment=iwtance and associate it_
wxh the Sale. @hat -- claT3.sh6;ld be fesponsibie
- - for this? since P O S T % C O ~ ~ Sa
k tthe real-world domain, t_he(2~_eatg-$&m suggests POST as a can-
~ a ~ & e in
didate for creating the Payment. me - - could then send an addpay-
-_Post instance
ment message to the Sale, passing along the new Payment as a parameter, as
shown in Figure 18.11.

.. _. 7.
;

1: create()---
,-. .,-:,:- .- ..- ..
p : Pavment
, , ,.
.".-.
L: y:
"

Figure 18.11 POST creates Payment.

This assignment of rego_nsibilities places the responsibility for making a pay-


ment in the POST The POST is taking on part of the responsibirity
-.-- -- -
for fulfilling
the makePaynzent system operation.
-
- thj? is a c c e p t d e , b u t i f w e sontiaue to make the POST
In this isolated example,
-

class responsible for doing s&e-or most of the work related t~-in;re and more
- -
system operations, it-will become
- --
increasingly burdened with tasks and becom
- -- - ---
incohes&,ve_.-
-
.- .-

.1magl<e that therewere fifty system oger&ns, ail --received by POST If i t dl


tlhe work related to each, it a o u l d h o m e a "bloated" incohesive object. ??.:
point is not that this single Payment creation task in itself makes the PUS
incohesive, bwt as part of a farger +&ire of~v-eral'lresponsibility assignment.
may suggest a t r ~ n dtoward iow cshesien.-- A
-/--

In contrast, as shown in Figure 18.12,.& second desr@delegates the paqmer


creation responsibility to the Sale, which sii@ortshigher cohesion in the PUS-
Since the second design supports both high cohesion and low coupling, it -
desirable.

Figure 18.12 Sale creates Payment.

In practice, the level of cohesion alone can not be considered in isolation fro?
other responsibilities and other principles such as Expert and Low Coupling.

Discussion Like Low Coupling, High Cohesion is a principle to keep in mind during a
design decisions; it is an underlying goal to continually consider. It is an e v a l u ~
tive pattern which a designer applies while evaluating all design decisions.
Grady Booch describes high functional cohesion as existing when the element
of a component (such as a class) "a14 work together to provide some well-bounder
behavior" [Booch94].
Here are some scenarios that illustrate varying degrees of functional cohesion:
1. Very loru cohesion. A class is solely responsible for many things in very dif
ferent functional areas.
o Assume a class exists called RDB-RPC-Interface which is corn
pletely responsible for interacting with relational databases ant
for handling remote procedure calls. These are two vastly differen
functional areas, and each requires lots of supporting code. Th
responsibilities should be split into a family of classes related t
RDB access and a family reIated to RPC suppod.
2. Low cohesion. A class has sole responsibility for a complex task in one h n c
tional area.
18 - GRASP: PATTERNS
FOR ASSIGNING RESPONSIBILITIES

o Assunie a class exists called RDBlnterface which is completely


responsible for interacting with relational databases. The methods
of the class are all related, but there are lots of them, and a tre-
mendous amount of supporting code; there may be hundreds or
thousands of methods. The class should split into a family of light-
weight classes sharing the work to provide RDB access.
3 . High cohesiort. A class has moderate responsibilities in one functional area
and collaborates with other classes to fulfill tasks.
o Assume a class exists called RDBbnterface which is only partially
responsible for interacting with relational databases. I t interacts
with a dozen other classes related to RDB access in order to
retrieve and save objects.
4 . Moderate cohesion. A class has lightweight and sole responsibilities in a few
different areas that are logically related to the class concept, but not to each
other.
o Assume a class exists called Company which is completely respon-
sible for (a) knowing its employees and (b) knowing its financial
.
information. These two areas are not strongly related to each
other, although both are logically related to the concept of a com-
pany. In addition, the total number of public methods is small, as
is the amount of supporting code.
As a rule of thumb, a class with high cohesion has a relatively small number of
By Atang Setiawan at 12:54 pm, May 05, 2008 methods, with highly related functionality, and does not do too much work. It
collaborates with other objects to share the effort if the task is large.
A class with high cohesion is advantageous because it is relatively easy to main-
tain, understand, and reuse. The high degree of related hnctionality, combined
with a small number of operations, also simplifies maintenance and enhance-
ments. The fine grain of highly related functionality also supports increased
reuse potential.
The High Cohesion pattern-like many things in object teclmology-has a real-
world analogy. It is a common observation that if a person takes on too many
unrelated responsibilities-especially ones that should properly be delegated to
others-then the person is not effective. This is observed in some managers who
have not learned how to delegate. These people suffer from low cohesion; they
are ready to become "unglued".

Benefits RI Clarity and ease of comprehension of the design is increased.


nr: Maintenance and enhancements are simplified.
m Low coupling is often supported.
ra The fine grain of highly related functionality supports increased reuse
potential because a highly cohesive class can be used for a very specific pur-
pose.

You might also like